1

First I want to make sure I'm understanding the behavior of what is happening when trying (and failing) to take a semaphore or mutex...

When this code runs (assuming xSemaphoreTake is going to fail to take the mutex), my understanding is that some_task would enter a blocked state for 1000 ticks then will be put into a ready state and again try to take some_mutex. BUT if only 500 ticks go by and the mutex is given, some_task would automatically enter the ready state. So what's the point of trying to take the mutex every so often (every 1000 ticks in this case) if the task will enter the ready state when the mutex is given regardless?

SemaphoreHandle_t some_mutex = xSemaphoreCreateMutex();

void some_task(void* parameters)
{
    xSemaphoreTake(some_mutex, (TickType_t) 1000);
    do_task_stuff();
    xSemaphoreGive(some_semaphore);
}

On a side note, does adding an if statement around xSemaphoreTake cause any difference in the behavior?

SemaphoreHandle_t some_mutex = xSemaphoreCreateMutex();

void some_task(void* parameters)
{
    if (xSemaphoreTake(some_mutex, (TickType_t) 1000) == pdPASS)
    {
        do_task_stuff();
    }
    xSemaphoreGive(some_semaphore);
}
3
  • Have a look at the docs and the example code freertos.org/Documentation/02-Kernel/04-API-references/… Commented Oct 9 at 17:52
  • @HS2 Thanks, I have, that's where my question came from. Something isn't clicking for me. I don't understand why you would want to poll the semaphore or even set a delay less than the max if the task will enter the ready state when the semaphore is free anyways. What's the point in coming back to check? Commented Oct 9 at 19:12
  • One might want a deadline wating for a mutex protected resource and run some error handling code in case the mutex/resource isn't released in time. Also I'd strongly recommend to always check the (error) return code of FreeRTOS API calls. Also note that you should release a mutex only if successfully aquired before (see the mentioned code example). Commented Oct 10 at 11:39

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.