Important changes to forums and questions
All forums and questions are now archived. To start a new conversation or read the latest updates go to forums.mbed.com.
9 years, 8 months ago.
Are RTOS mutexes reenterant (recursive)?
Subj
I.e. if there is
void foo() { mutex.lock(); .... bar(); .. mutex.unlock(); }
void bar() { mutex.lock(); .. mutex.unlock(); }
will the foo() work OK (inner lock()/unlock() has no effect) or will it be stalled on second lock() in bar() or will it free the mutex too early on the first unlock() in bar()?
Question relating to:
2 Answers
9 years, 7 months ago.
The mbed-rtos library isn't kind enough to let user know whether mutex is reenterant or not. I think that is safe not to use rtos with assumption of reenterant supported.
9 years, 7 months ago.
mbed-rtos using RTx, there's documentation, source code, so anyone can look at the code , which can asnwer the questions.
Mutex can be unlocked only by the task which has an ownership. ARe foo and bar executed from the current task - theg same one?
One resource about recursive mutexes and why they might not be a good solution http://www.zaval.org/resources/library/butenhof1.html
2 Martin:
Yes, in the example foo() and bar() are executed by the same task (thread).
Ownership is not enough for proper unlocking though - at least a lock/unlock counter must exists somewhere, otherwise unlock() in bar() will release the mutex too early.
Wrt link: "A correct and well understood design does not require recursive mutexes." With all my respect, this is a very ... arrogant statement. The design is not only locking.
If both foo() and bar() are public methods which can be called on its own, from same or different threads, avoiding recursive mutexes will at least produce less cleaner code.
Consider for example, that foo() calls some callback function (an Observer) in a locked context, which may in turn call bar(). It is still possible to avoid recursive locking here, but it will be a pain of flags and checks and overloads (and bugs).
posted by Anatoly Kochubey 24 Mar 2015