Section 9.5

Mutex

Full name: Mutual exclusion lock.

Definition

A mutex, short for mutual exclusion lock, is a synchronization object that at most one thread can hold at a time; a thread is a sequence of instructions that the operating system schedules. A thread locks the mutex before it uses the data the mutex guards, and unlocks it afterwards. A thread that tries to lock a held mutex is suspended until the mutex is free, instead of using the processor while it waits. A mutex has an owner: only the thread that locked it may unlock it.

The idea

Two threads add entries to one shared list. Adding an entry takes several steps, and if the threads interleave those steps, entries are lost or the list is corrupted. The threads need a critical section §9.4, a region of code that only one of them may be in at a time. Masking interrupts §6.11 would provide one, but it would also hold back every unrelated interrupt for the whole time. Spinning, testing a flag again and again, would waste the processor that the holder needs in order to finish. A mutex lets the second thread sleep: the operating system stops running it until the holder unlocks, and runs other work meanwhile.

The picture is a room with one key and a waiting line. The key holder is inside; the others queue at the door and doze until the key comes back. Two details of the picture carry over exactly. Only the holder returns the key, which is the owner rule. And the key controls only the door, so anyone who reaches the shared data without using the mutex is not stopped. The picture stops being accurate at one point: a mutex does not in general serve waiters first come, first served. Which waiter gets the key next is a policy of the operating system.

How it works

A mutex holds three pieces of state: whether it is locked, which thread owns it, and a wait queue, the list of threads suspended until it is unlocked. A recursive mutex also holds a lock count.

  1. Lock, free case. The thread changes the state from unlocked to locked and records itself as owner. It uses an atomic compare-and-swap §9.9, an instruction that writes a new value only if memory still holds the expected old value, so that two threads cannot both succeed.

  2. Lock, held case. The thread asks the operating system to put it in the wait queue and suspend it. The scheduler, the part of the operating system that decides which thread runs, runs another thread. A lock call with a timeout §9.34 gives up when the time has passed and returns an error code; the thread then does not own the mutex and must not touch the data.

  3. Unlock. The owner gives up the mutex. If threads are waiting, the operating system wakes one of them. In Zephyr §6.33, a real-time operating system for small devices, the mutex passes directly to the waiting thread with the highest priority, and among threads of equal priority to the one that has waited longest.

  4. Memory order. Locking has acquire semantics and unlocking has release semantics: everything the previous owner wrote before it unlocked is visible to the next owner after it locks. In C11, the 2011 edition of the C standard, every earlier unlock of a mutex synchronizes with a later lock of the same mutex.

The owner record makes two features possible that other locks lack. Error checking: an unlock by a thread that does not own the mutex can be refused; Zephyr’s k_mutex_unlock then returns the error code -EPERM. Priority inheritance §9.17: while a thread of higher priority waits for the mutex, the operating system temporarily raises the owner to the waiter’s priority, so that threads of middle priority cannot keep the owner, and with it the waiter, from running. Zephyr mutexes do this.

What happens when the owner locks again depends on the kind of mutex. A recursive mutex counts: each lock by the owner adds 1, each unlock subtracts 1, and other threads can lock it only when the count is back at 0. Zephyr’s mutex is recursive. A non-recursive mutex has no count. In C11, a thread must not lock a non-recursive mutex that it already holds; doing so has undefined behavior §4.12. In POSIX (Portable Operating System Interface), the standard interface of Unix-like systems, a mutex of type PTHREAD_MUTEX_NORMAL makes the thread wait for itself forever, a mutex of type PTHREAD_MUTEX_ERRORCHECK returns an error, and a mutex of type PTHREAD_MUTEX_RECURSIVE counts.

An interrupt service routine §6.12 (ISR), the routine the processor runs when a device raises an interrupt, cannot use such a mutex. An ISR is not a thread: the scheduler cannot suspend it, and the code it interrupted cannot continue until it returns, so an ISR that waited for a mutex held by that code would wait forever, as the worked example shows. Priority inheritance also needs an owner thread whose priority can be raised. Zephyr’s documentation states that mutex objects are not designed for use by ISRs. Data shared with an ISR is protected instead by masking that interrupt while a thread uses the data, by a spinlock §9.7 taken with interrupts masked, or by passing the work to a thread through a semaphore §9.6 or a queue.

Worked example

Thread A uses a Zephyr mutex M, which is recursive.

  1. A locks M: the count goes from 0 to 1, and the owner is A.

  2. A calls a helper function §2.19 that also locks M. The owner is A, so the count goes from 1 to 2 and A continues without waiting.

  3. Thread B tries to lock M. The owner is A, so B is suspended.

  4. The helper unlocks M: the count goes from 2 to 1. M is still owned by A, and B still waits.

  5. A unlocks M: the count goes from 1 to 0. M passes to B, with count 1 and owner B, and B becomes ready to run.

With a non-recursive mutex, step 2 has no count to increase. A plain C11 mutex makes it undefined behavior, and a PTHREAD_MUTEX_NORMAL mutex leaves A waiting for itself forever. That is a deadlock §9.14, a state in which activities wait for each other and none can proceed.

On a single-core processor, thread T locks a non-recursive mutex M and starts updating a list. An interrupt arrives, and its ISR calls lock on M. M is held by T, so the ISR would have to wait. T can run again only after the ISR returns. The ISR waits for T and T waits for the ISR, so neither ever proceeds. A kernel may detect the misuse and report an error, but it cannot make the wait succeed.

Priority inheritance in numbers: thread Low holds M and needs 1 ms more to finish its critical section. Thread High asks for M and is suspended. Thread Mid, whose priority lies between the two, becomes ready and computes for 50 ms. Without priority inheritance, Mid preempts Low, so High waits 50+1=5150 + 1 = 51 ms. With priority inheritance, Low runs at High’s priority, Mid cannot preempt it, and High waits 1 ms.

Stated precisely

The C11 standard, in section 7.26.4, states the contract of its mutex. mtx_lock “blocks until it locks the mutex”. If the mutex is non-recursive, “it shall not be locked by the calling thread” beforehand. “Prior calls to mtx_unlock on the same mutex shall synchronize with this operation.” And mtx_unlock requires that the mutex “shall be locked by the calling thread”. Combined with the happens-before relation §9.10, the order that synchronization creates between threads, these rules give two guarantees.

The guarantees protect the data only under three assumptions.

  1. Every access to the guarded data, by every thread, happens while that thread holds the same mutex.

  2. No ISR and no hardware, such as a direct memory access §4.36 (DMA) engine, which copies data in memory without the processor, accesses the data.

  3. The mutex object exists, initialized, for as long as any thread uses it or waits on it; Zephyr’s documentation forbids freeing or reusing a mutex while it is locked or while threads wait on it.

A lock call that fails, returns busy or times out grants nothing.

Limits and common mistakes

A recursive mutex makes a lock call from an ISR more dangerous, not less. If the kernel identified the caller by the thread that is currently running, which during the ISR is still the interrupted thread, a mutex held by that thread would see its owner locking again and would admit the ISR into the half-finished update. The call must be forbidden, not trusted.

A mutex guards data only by convention. Nothing stops code that forgets to lock it, and the data’s declaration does not say which mutex guards it unless the program states that in a form a tool can check.

Two threads that lock two mutexes in opposite orders can each hold one and wait for the other: a deadlock. Lock ordering §9.15, a single fixed order in which all code takes the mutexes, prevents it.

Without priority inheritance, a thread of middle priority can delay a high-priority waiter for as long as it computes; this is priority inversion §9.16. Priority inheritance bounds the delay but does not remove the wait for the owner’s own critical section.

A pointer to guarded data that is kept after the unlock is no longer guarded. Another thread may change or free the object it points to, a matter of object lifetime §4.1.

Holding a mutex across slow operations, such as waiting for a radio or for flash memory §6.6, makes every other user of the mutex wait as long.

Not every mutex serves waiters in arrival order. A thread can wait a long time while other threads take the mutex again and again, which is called starvation §9.18.

A recursive mutex can hide a design error. A function that locks a mutex its caller already holds cannot assume that the data is consistent on entry, because the caller may be halfway through an update.

Questions answered

Can this mutex be acquired from an ISR or recursively?

From an interrupt service routine (ISR), the routine the processor runs when a device raises an interrupt: no, for the usual sleeping mutex of an operating system. An ISR is not a thread and cannot be suspended, and if the thread it interrupted holds the mutex, the ISR would wait for a thread that cannot run until the ISR returns. Zephyr’s documentation states that its mutex objects are not designed for use by ISRs, and C11 and POSIX (Portable Operating System Interface) define their mutexes for use between threads, not from signal handlers, their nearest equivalent of an ISR. Share data with an ISR through interrupt masking, through a spinlock taken with interrupts masked, or by handing work to a thread through a semaphore or a queue.

Recursively: only if the mutex is of a recursive kind. A recursive mutex counts its owner’s locks and becomes free only after the same number of unlocks. Zephyr’s mutex, a C11 mutex created with mtx_recursive, and a POSIX mutex of type PTHREAD_MUTEX_RECURSIVE behave this way. On a non-recursive mutex, a second lock by the owner has undefined behavior in C11, makes the thread wait for itself forever with the POSIX normal type, and returns an error with the POSIX error-checking type. For any particular mutex, its interface documentation must state both points, and the answer comes from there.

Related entries: Critical section (§9.4), Semaphore (§9.6), Priority inversion (§9.16), Object lifetime (§4.1), Priority inheritance (§9.17), Deadlock (§9.14). Further reading: [78, 83].