TaskSuspendAll Vs Mutex

mkchampion wrote on Monday, December 17, 2012:

I am new to using an RTOS so please execuse my ignorance.

Why would you use a mutex instead of TaskSuspendAll for task synchronization if I don’t need to worry about sync between task and ISR?  Initially I though mutex is more efficient but it seems like xSemaphore calls TaskSuspendAll anyway?

/* Interrupts and other tasks can send to and receive from the queue
now the critical section has been exited. */

prvLockQueue( pxQueue );

richard_damon wrote on Monday, December 17, 2012:

vTaskSuspendAll() is used to make sure the the following code occurs without interruption by other tasks, but not stopping interrupts from occurring.

A mutex on the other hand only interlocks with other tasks that test the same mutex, and if another task has the mutex, blocks the current task ( vTaskSuspendAll() will never block). Note also that a task that has called vTaskSuspendAll() shouldn’t block while a task using a semaphore can safely block (as long as you aren’t blocking on something that will require another task to acquire the mutex you hold).

Note that the code you quoted lists the other type of interlock, a critical section, which disables interrupts so that not even interrupts can interfere with the code running.

mkchampion wrote on Monday, December 17, 2012:

Thanks for the reply richard.  What I want to achieve is one thread is writing to the variables and the other thread reads them.  The operation is quite short but I need to make sure that a write does not happen while a read is happening (or vice versa).  Would a critical section implemented by TaskSuspendAll be appropriote (if I am not worried about ISR)?  Could you confirm that the semaphore/mutex all call TaskSuspendAll?  I was worried that the TaskResumeAll will take a long time but if it is going to be called anyway I may as well just use it as the critical section is very short.

BTW, the code I copied was in xQueueGenericReceive (queue.c) which is called by xSemaphoreTake.

Many thanks.

richard_damon wrote on Monday, December 17, 2012:

If it is only for a few instructions, then a critical section is likely the best option (vTaskEnterCritical). This is basically that disables the interrupts, and then re-enables them when your are done. The limitation is that by disabling interrupts, you increase the interrupt response latency possible, thus best to use only for short actions.

I would need to look closer at the code, but I suspect that a mutex/semaphore call will not always hit the TaskSuspendAll call, and that taking or giving an uncontested mutex will not enter that piece of code, but only due that if it needs to walk the list of tasks to see who needs to be unblocked. User code rarely needs to call TaskSuspendAll directly, but normally is better served with semaphores/mutexes for longer interlocks, and critical sections for the very short ones.