Mutex and tasks with different priorities

Hello, I have two tasks which use the same serial port. I prepared two functions one for “locking”, second for “unlocking” (see example bellow). I used the mutex “serLockMutex” for synchronization of usage of serial port. These functions are called from both tasks. When both tasks have the same priority, everything work’s well. When I use higher priority for TASK1, there is a problem. TASK1 (priority 2) don’t stop on xSemaphoreTake() to wait when the TASK2 (priority 1) released the mutex “serLockMutex”. Many thank’s in advance for your support. Zdenek Example of functions, usefull for only one serial channel SemaphoreHandle_t serLockMutex = NULL; ~~~ void serLockFreeRTOS (unsigned short channel, TaskHandlet notifyToTask) { if (serLockMutex == NULL) { serLockMutex = xSemaphoreCreateMutex(); vQueueAddToRegistry( serLockMutex, “LockMutex” ); } if (serLockMutex == NULL) { MACERROR_LOOP; } xSemaphoreTake( serLockMutex, portMAX_DELAY ); ser[channel].notify = notifyToTask; } void serUnLockFreeRTOS (unsigned short channel) { xSemaphoreGive (serLockMutex); ser[channel].notify = NULL; } ~~~

Mutex and tasks with different priorities

To make sure I understand what you are reporting – are you saying that when the tasks have different priorities the call to xSemaphoreTake( serLockMutex, portMAX_DELAY ); returns even when it doesn’t have the mutex? Does the function return pdTRUE, so it thinks it has the mutex? If this is the case then there could be a logic error somewhere in the code where you are calling these functions, and the task that has the mutex is not the one you think it is – or it could be a simple data corruption somewhere. Do you have configASSERT() defined (and are you using a recent version of FreeRTOS, which has a lot more assert points to trap potential configuration errors)? Not sure that it is related to your issue, but from the very brief snippet of code you have posted it seems you might have a logic error that could result in a race condition. In serUnLockFreeRTOS() you give the semaphore back before setting ser[channel].notify to NULL. Is that correct?

Mutex and tasks with different priorities

Thank’s for your quick answer. I found my mistake. The problem was with giving back mutex before setting ser[channel].notify to NULL. We are moving our project from old one cooperative OS to FreeRTOS and I need more time to understand what really means PREEMPTIVE. Many thank’s one more. Zdenek