Search code examples
tasksemaphorefreertos

How to know which task has taken a binary semaphore?


I have three tasks, which shares a binary semaphore myBinarySemaphore. I'd like to know which task is currently having the binary semaphore. I could use a global variable to do this but does freeRTOS provide a method for this ?

Here's the code, I'm looking for a freeRTOS method to check which task has the binarySemaphore, in taskC for example. xTaskOwner is pure invention for example purpose. Thanks.

    void taskA(void *pvParameters)
    {
        for(;;)
        {
            if(xSemaphoreTake(myBinarySemaphore, (TickType_t) 10) == pdTRUE)
            {
                xSemaphoreGive(myBinarySemaphore);
            }
        }
    }
    
    void taskB(void *pvParameters)
    {
        for(;;)
        {
            if(xSemaphoreTake(myBinarySemaphore, (TickType_t) 10) == pdTRUE)
            {
                xSemaphoreGive(myBinarySemaphore);
            }
        }
    }
    
    void taskC(void *pvParameters)
    {
        for(;;)
        {
            if(xTaskOwner(myBinarySemaphore) == taskA) // <== How to check with freeRTOS which task has the semaphore ? 
                printf("taskA has the semaphore");
            else if (xTaskOwner(myBinarySemaphore) == taskB)
                printf("taskB has the semaphore");
        }
    }

PS & EDIT: let's assume that taskC can be run simultaneously than the other tasks, because otherwise my example is wrong.


Solution

  • I would add a Queue with a simple message in it that says which task currently has the semaphore. Every time you take the semaphore, you overwrite the queue. In taskC you can do a xQueuePeek and see which task did the overwrite.

    OR

    You can use event flags to signal which task has the semaphore. Each task has its own flag on a share event group.