Mutex API
The Mutex API provides standard mutex functionality with added diagnostics capabilities. These mutexes can be shared by threads within the same process, but can't be shared by threads in different processes.
- Warning
- Multithreaded programming is an advanced subject with many pitfalls. A general discussion of why and how mutexes are used in multithreaded programming is beyond the scope of this documentation. If you are not familiar with these concepts please seek out training and mentorship before attempting to work on multithreaded production code.
Two kinds of mutex are supported by Legato:
- Recursive or
- Non-Recursive
All mutexes can be locked and unlocked. The same lock, unlock, and delete functions work for all the mutexes, regardless of what type they are.
A recursive mutex can be locked again by the same thread that already has the lock, but a non-recursive mutex can only be locked once before being unlocked.
If a thread grabs a non-recursive mutex lock and then tries to grab that same lock again, a deadlock occurs. Legato's non-recursive mutexes will detect this deadlock, log a fatal error and terminate the process.
If a thread grabs a recursive mutex, and then the same thread grabs the same lock again, the mutex's "lock count" is incremented. When the thread unlocks that mutex, the lock count is decremented. Only when the lock count reaches zero will the mutex actually unlock.
There's a limit to the number of times the same recursive mutex can be locked by the same thread without ever unlocking it, but that limit is so high (at least 2 billion), if that much recursion is going on, there are other, more serious problems with the program.
Creating a Mutex
In Legato, mutexes are dynamically allocated objects. Functions that create them return references to them (of type le_mutex_Ref_t).
Functions for creating mutexes:
le_mutex_CreateRecursive()
- creates a recursive mutex.le_mutex_CreateNonRecursive()
- creates a non-recursive mutex.
All mutexes have names, required for diagnostic purposes. See Diagnostics below.
Using a Mutex
Functions for locking and unlocking mutexes:
It doesn't matter what type of mutex you are using, you still use the same functions for locking and unlocking your mutex.
Deleting a Mutex
When you are finished with a mutex, you must delete it by calling le_mutex_Delete().
There must not be anyone using the mutex when it is deleted (i.e., no one can be holding it).
Diagnostics
The command-line diagnostic tool inspect can be used to list the mutexes that currently exist inside a given process. The state of each mutex can be seen, including a list of any threads that might be waiting for that mutex.
Copyright (C) Sierra Wireless Inc.