[riot-devel] Mutex and thread priority

Juan Ignacio Carrano j.carrano at fu-berlin.de
Thu Nov 22 12:49:26 CET 2018


Hi Baptiste,

On 11/22/18 12:11 PM, Baptiste Clenet wrote:
> Hi,
> I have looked at mutex.c and thread.c and I've understood that a
> thread with higher priority (it has priority) will unlock the mutex
> even if thread with lower priority has not finished/unlock the mutex?
> Am I right?

You are referring to a situation in which a thread unlocks a mutex it 
did not lock before?

In that case the mutex is not behaving as such, but rather as a generic
lock, and any thread can unlock it. See 
https://github.com/RIOT-OS/RIOT/issues/9594 .

If you want the mutex to actually behave as a mutex you should ensure 
you never have an unlock without a matching lock (i.e. that the only 
thread that can unlock a mutex is the one that locked it and thus own 
it). RIOT's mutexes do not enforce that, so you must resolve it by 
careful usage.

> Now, in my case, I use UART with ethos (which use a mutex) and what
> happens on my case is:
> * I have thread A (high priority), thread B (low priority)
> * B starts to write on UART an long str
> * A wants to write on UART an lock the mutex (ethos) but because it
> has higher priority, it sends its message over UART until end of str
> * B can continue and finish to send its str
> 

So you are saying that the lower priority "B" thread is being preempted 
and it's output interrupted by A's output?

I'm not familiar with ethos, but my intuition is that, while it may have 
a mutex, it may not be programmed in a way that the UART access is 
exclusive too. Exclusive access to UART would not be a good idea as in 
cases like yours it opens the door to priority inversions.

> So I'm wondering why a thread with higher priority should be able to
> unlock a mutex locked by a thread with lower priorty?
> 

Actually any thread can unlock a mutex locked by another thread. What 
can never happen is that a thread _locks_ a mutex locked by another 
thread. In your mind, replace the word "mutex" with "lock" and things 
may become clearer.

Regards,

Juan.


More information about the devel mailing list