43.2 Mutexes

Mutually exclusive locks (or mutexes) serialize access to a shared state by assuring a single, exclusive owner (one thread at a time). To enhance concurrency when the shared state is mostly read only, we also support reader-writer locks (see Section 43.3, Reader-Writer Locks).

Mutexes are also called sleep locks because they put to sleep any thread that contends unsuccessfully for a lock. All threads that contend for a mutex are placed on a sleep queue and awakened one-by-one with a mutex acquisition. Acquiring a mutex means that the resource protected by it can now be manipulated by the owning (acquiring) thread. Because LibC is designed to be hosted both within the kernel and in user space, how a thread sleeps while waiting for a contested lock is not specified.

To deal with locking-related deadlock issues, LibC supports hierarchy with respect to locks. You can specify the order in which you expect to acquire the application-defined locks and this order is asserted by LibC in debug mode.

To support performance tuning and debugging, the system also collects statistics with respect to locks (if appropriate compilation switches are defined).

An example of a resource that might be protected by a mutex is the linked list. If a linked list is highly dynamic or frequently changed and if the changes are performed by potentially more than one thread, a mutex might be a good way to serialize access to it.

If a high-priority thread is contesting a mutex with low-priority threads, the higher priority thread should be positioned to acquire the mutex first.

The mutex is the cheapest of all LibC synchronization variables in terms of overhead, work to acquire, etc. It is a good idea to make variables part of the implementation design document for locking code and update that document only after you determine that a different variable type would be better in that situation.

LibC supports mutexes on the NKS, pthreads, and UI interfaces:

For a list of the functions supported by these interfaces, see Mutex Interface Comparison.