taking a mutex multiple times

hooverphonique wrote on Thursday, September 18, 2008:

the mutex documentation says:
"This means the mutex must always be ‘given’ back - otherwise the higher priority task will never be able to obtain the mutex, and the lower priority task will never ‘disinherit’ the priority. An example of a mutex being used to implement mutual exclusion is provided on the xSemaphoreTake() documentation page. "

which implies that a task can take a mutex as many times as it wants and then give it back once, when done with it…

Is this a correct observation? (note: i’m talking regular mutexes, not recursive ones.)

cheers…

davedoors wrote on Thursday, September 18, 2008:

Mutexes are like binary semaphores in that they are either available or not. You can take it as many times as you like but only the first take call will return pdTRUE assuming the mutex was available. Following calls will return pdFALSE until you have given the semaphore back.

hooverphonique wrote on Thursday, September 18, 2008:

ok… what i was after was a "reentrant" mutex that can be taken succesfully an infinite number of times by the same task (assuming it is initially available)…

davedoors wrote on Thursday, September 18, 2008:

I think that would be easy enough to implement. The mutuex holder is saved in the pxMutexHolder member so if the same task takes the mutuex but is already the mutuex holder it can return true. It might be better to keep the FreeRTOS code unchanged, and provide your own wrapper to the take function to add in this extra functionality.

hooverphonique wrote on Friday, October 03, 2008:

That looks easy enough, yah… only thing is, the xQUEUE type is private to FreeRTOS, so the wrapper would have to be a hack…

richard, if you read this:

maybe it would be an idea to have a function in the API like

xMutexTake(xSemaphoreHandle, portTickType, portBASE_TYPE reentrant);

that would just call xSemaphoreTake if reentrant is false and use xTaskGetCurrentTaskHandle to check pxMutexHolder if true and then skip calling xSemaphoreTake if the current task is already the owner…

cheers…