Mutex unlock order misunderstannding

Discussions and support about ChibiOS/RT, the free embedded RTOS.
Post Reply
Ceco
Posts: 40
Joined: Tue Nov 27, 2012 12:16 pm
Been thanked: 3 times

Mutex unlock order misunderstannding

Post by Ceco »

Hello.

In latest Chibios RT we can unlock specified mutex i.e. chMtxUnlock takes a parameter mutex pointer. Which is great.

But in the general explanation we still have the following lines:

* <h2>Constraints</h2>
* In ChibiOS/RT the Unlock operations must always be performed
* in lock-reverse order. This restriction both improves the
* performance and is required for an efficient implementation
* of the priority inheritance mechanism.<br>
* Operating under this restriction also ensures that deadlocks
* are no possible.

So I'm a bit forked. Is it obligatory to release mutexes in strict revers order or not?
User avatar
Giovanni
Site Admin
Posts: 14891
Joined: Wed May 27, 2009 8:48 am
Has thanked: 1202 times
Been thanked: 996 times

Re: Mutex unlock order misunderstannding

Post by Giovanni »

Hi,

Yes, it is still mandatory, the parameter has been added in order to check for possible errors or misunderstandings (checked via an assertion so no overhead) and also for compatibility with other API (Posix).

Note that we could lift this constraint but releasing mutexes in an order other than the reverse of acquisition must be considered a programming error, doing so could lead to deadlocks hard to debug. Note that releasing in a different order should never be required.

It is one of those cases where we prefer to enforce good practices, other examples are:
1) Killing threads is not allowed.
2) Changing priority of other threads is not allowed.

Not technical limitations but choices in name of intrinsic safety.

Giovanni
Ceco
Posts: 40
Joined: Tue Nov 27, 2012 12:16 pm
Been thanked: 3 times

Re: Mutex unlock order misunderstannding

Post by Ceco »

I understand now. Thanks!
User avatar
Giovanni
Site Admin
Posts: 14891
Joined: Wed May 27, 2009 8:48 am
Has thanked: 1202 times
Been thanked: 996 times

Re: Mutex unlock order misunderstannding

Post by Giovanni »

You are welcome.

Note that releasing mutexes in reverse order is necessary but not sufficient to prevent deadlocks. It greatly improves the mutexes handling anyway. Without this the "priority inheritance" algorithm complexity would grow of a +N.

Giovanni
Post Reply