CSE Roadmap

Core tier · about 5 hours · 7 parts

Part 5 of 7 · 2 min read

Kinds

In plain words: A door lock can be a plain one, a lock that complains if the owner tries to lock a door twice, or a lock that counts how many times its owner has locked it and opens only when each lock has a matching unlock. These are three mutex types, chosen with an attribute.

Type Locking it twice by the same thread Unlocking when not the owner
PTHREAD_MUTEX_NORMAL (default) Deadlock (the thread waits for itself) Undefined behaviour
PTHREAD_MUTEX_ERRORCHECK Returns EDEADLK Returns EPERM
PTHREAD_MUTEX_RECURSIVE Succeeds, with a count Returns EPERM

Test output:

error-checking mutex, locked twice by one thread: Resource deadlock avoided
recursive mutex, locked twice: return 0; needs two unlocks
unlock of a recursive mutex that is not held: Operation not permitted

The error-checking type is good while testing, since a self-deadlock appears as an error, not as a hung program. A recursive mutex can be locked again by its owner, and it is released when the number of unlocks equals the number of locks. It is useful when a function that holds the lock calls another function that locks the same mutex. Many experts treat it as a sign of unclear design, since it hides the question of which function protects what, and it is slower.

Further attributes exist. A mutex can use priority inheritance (PTHREAD_PRIO_INHERIT) against the priority inversion of Level 3, page 4. A robust mutex reports EOWNERDEAD if its holder died while holding it, so the next owner can repair the data.

Common errors:

  • Forgetting to unlock on an early return or an error path. The next thread waits for ever. Use a single exit point.
  • Locking twice (default type): the thread blocks for ever.
  • Unlocking a mutex that is not held, or one held by another thread: undefined behaviour for the default type.
  • Using a lock after destroying it, or copying a mutex: a copy is a different lock.
  • Locking in a signal handler: a handler that interrupts the lock holder and then locks the same mutex waits for itself. Mutex functions are not safe in handlers (Level 1, page 6).

Recursive mutex

A recursive mutex is a mutex that its owning thread may lock several times, keeping a count of the locks, and which becomes free only when the owner has unlocked it as many times as it locked it.

Example: a thread that locks a recursive mutex twice and unlocks it once still holds the lock; the second unlock frees it.

Check yourself: 1. What happens when a thread locks a default mutex twice? 2. What does the error-checking type return in that case? 3. Why can a signal handler not safely lock a mutex?