I have a quick question. As semaphores are implemented as queues, is there any reason why uxQueueMessagesWaiting() can’t be used to determine is a semaphore is able to be given/taken without actually giving/taking it?
Thanks for that. It compiles OK, but doesn’t seem to do what I wanted it to do. Turns out what I really need to know is “has a task already given the semaphore”, not “is the semaphore able to be given”.
Using uxQueueMessagesWaiting to get a semaphore’s count works as expected for me. Here is a demo excerpt:
// uxQueueMessagesWaiting Demo
int dummy_value = 3;
xQueueHandle demo_queue = xQueueCreate(5, sizeof(int));
// Initial size is 0
if (demo_queue != NULL)
{
unsigned int q_size = uxQueueMessagesWaiting(demo_queue);
// Output q_size here; should be 0
}
// Push 3 items
portBASE_TYPE xStatus;
xStatus = xQueueSendToBack(demo_queue, &dummy_value, 0);
xStatus = xQueueSendToBack(demo_queue, &dummy_value, 0);
xStatus = xQueueSendToBack(demo_queue, &dummy_value, 0);
// New size is 3
if (xStatus == pdPASS)
{
unsigned int q_size = uxQueueMessagesWaiting(demo_queue);
// Output q_size here; should be 3
}
Which yields the expected output of 0 and 3.
From my tests, the number of tasks pending on a semaphore does not seem to impact the count.
Note: Using uxQueueMessagesWaiting with semaphores seems to be undocumented, unless I missed something.
Edit: I realized that my sample didn’t actually use a Semaphore. The following sample verifies uxQueueMessagesWaiting for semaphores with both zero and non-zero init_count.
// semaphore queue size demo
SemaphoreHandle_t semaphore_handle1 = xSemaphoreCreateCounting(20, 0);
if (semaphore_handle1 != NULL)
{
unsigned int q_size = uxQueueMessagesWaiting(semaphore_handle1);
// Output q_size here; should be 3
xSemaphoreGive(semaphore_handle1);
xSemaphoreGive(semaphore_handle1);
xSemaphoreGive(semaphore_handle1);
q_size = uxQueueMessagesWaiting(semaphore_handle1);
// Output q_size here; should be 0
}
// semaphore queue size demo (with init_count > 0)
SemaphoreHandle_t semaphore_handle2 = xSemaphoreCreateCounting(20, 5);
if (semaphore_handle2 != NULL)
{
unsigned int q_size = uxQueueMessagesWaiting(semaphore_handle2);
// Output q_size here; should be 5
// Give 3
xSemaphoreGive(semaphore_handle2);
xSemaphoreGive(semaphore_handle2);
xSemaphoreGive(semaphore_handle2);
q_size = uxQueueMessagesWaiting(semaphore_handle2);
// Output q_size here; should be 3
// Take 4
xSemaphoreTake(semaphore_handle2, portMAX_DELAY);
xSemaphoreTake(semaphore_handle2, portMAX_DELAY);
xSemaphoreTake(semaphore_handle2, portMAX_DELAY);
xSemaphoreTake(semaphore_handle2, portMAX_DELAY);
q_size = uxQueueMessagesWaiting(semaphore_handle2);
// Output q_size here; should be 4
}
Output:
Semaphore Size (init_count == 0):0
After giving 3 times:3
Semaphore Size (init_count == 5):5
After giving 3 times:8
After taking 4 times:4