What is a counting semaphore?
Short answer: A semaphore whose count can go above one. Each take decrements the count (blocking at zero) and each give increments it. It is used for resource counting (initialise it to N for N identical resources) and for event counting (an ISR gives once per event, so events that arrive faster than the task handles them are not lost).
Resource counting example: a pool of 4 DMA buffers
SemaphoreHandle_t buf_sem = xSemaphoreCreateCounting(4, 4); /* max 4, initially 4 free */
uint8_t *buf_get(void)
{
if (xSemaphoreTake(buf_sem, pdMS_TO_TICKS(50)) != pdTRUE) return NULL; /* none free */
return pool_alloc(); /* guaranteed to succeed now */
}
void buf_put(uint8_t *b) { pool_free(b); xSemaphoreGive(buf_sem); }
Event counting example: a UART ISR gives the semaphore for each received line; the processing task takes it once per line. With a binary semaphore, two lines arriving before the task runs would count as one.
Limits: the count has a maximum (set at creation); giving beyond it fails. The semaphore carries no data, only a count: if you need the data too, use a queue.
Alternatives: FreeRTOS task notifications can act as a lightweight counting semaphore for a single waiting task (ulTaskNotifyTake(pdFALSE, ...) decrements by one).