SemaphoreHandle_t xSemaphore = xSemaphoreCreateCounting(3, 3); // Four tasks call xSemaphoreTake(xSemaphore, portMAX_DELAY) one after another
A counting semaphore with initial count 3 allows up to 3 tasks to take it without blocking. The fourth task must wait until one of the first three tasks releases (gives) the semaphore.
SemaphoreHandle_t xSemaphore = xSemaphoreCreateCounting(5, 2); xSemaphoreTake(xSemaphore, 0); xSemaphoreGive(xSemaphore); xSemaphoreGive(xSemaphore); xSemaphoreTake(xSemaphore, 0); xSemaphoreTake(xSemaphore, 0); xSemaphoreTake(xSemaphore, 0);
Initial count is 2. After one take, count is 1. Two gives increase count to 3 (max 5). Three takes reduce count to 0.
SemaphoreHandle_t xSemaphore = xSemaphoreCreateCounting(2, 2); void task(void *params) { if (xSemaphoreTake(xSemaphore, portMAX_DELAY) == pdTRUE) { // Use resource // Missing xSemaphoreGive(xSemaphore); } vTaskDelete(NULL); }
If a task takes the semaphore but never gives it back, the count never increases. Other tasks waiting to take the semaphore will block forever, causing deadlock.
The function xSemaphoreCreateCounting takes two parameters: max count and initial count. Option A uses correct order and number of parameters.
A counting semaphore with max and initial count equal to the number of resources correctly limits concurrent access. Tasks block when all resources are busy and unblock when one is released.
