Synchronization

a mutex (lock)

/ MYOO-teks /

A mutex is the everyday lock that makes mutual exclusion real. The name is short for 'mutual exclusion'. Think of it as a single key hanging on a hook: before touching shared data you grab the key (lock), do your work, then hang it back (unlock). While you hold the key, no other thread can get it — they wait at the hook. There is exactly one key, so exactly one thread can be inside the protected region at a time.

A mutex has two operations, usually called lock and unlock (also spelled acquire and release). Calling pthread_mutex_lock() either succeeds immediately, if the mutex is free, or blocks the calling thread — puts it to sleep — until whoever holds the mutex calls pthread_mutex_unlock(). When a thread has successfully locked a mutex and not yet unlocked it, we say it is holding the lock; while it holds the lock, it is the only thread allowed in the critical section. The pattern is always lock, then a short critical section, then unlock — and crucially you must unlock on every path out, including early returns and errors, or other threads wait forever.

Mutexes are the workhorse of concurrent code: the default tool for protecting any shared mutable state. Two caveats matter. A plain mutex is not recursive — if the thread that already holds it calls lock again, it deadlocks against itself (use a recursive mutex if you truly need re-entry). And a mutex protects whatever data you decide it protects: the connection between the lock and the data it guards lives only in your head and your comments, never in the compiler. If you forget to take the lock in one place, the mutex cannot save you.

pthread_mutex_lock(&m); balance = balance + amount; pthread_mutex_unlock(&m); — the deposit happens entirely inside the lock, so two threads depositing at once cannot clobber each other's update.

Lock, do the smallest critical section, unlock on every exit path.

Only the thread that locked a normal mutex may unlock it — a mutex is owned, unlike a semaphore which any thread can post. Holding a lock longer than necessary, or doing slow work (file I/O, blocking calls) while holding it, serialises your whole program and quietly destroys performance.

Also called
lockmutual-exclusion lock互斥量