C Reference ยท POSIX and Systems
C pthread_mutex functions
Reference for POSIX mutexes: pthread_mutex_init, lock, trylock and unlock, how they prevent data races, mutex types, deadlock rules and error codes.
A mutex (mutual exclusion lock) lets only one thread at a time run a critical section. A thread calls pthread_mutex_lock() before touching shared data and pthread_mutex_unlock() afterwards. If another thread already holds the lock, the caller blocks until it is released. Used consistently, a mutex turns a data race into well-defined, ordered access.
The rule that makes it work: every access to a piece of shared data, reads included, must happen while holding the same mutex. A lock on only one side protects nothing.
#include <pthread.h> pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_lock(&lock); /* ... touch shared data ... */ pthread_mutex_unlock(&lock);
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Syntax
#include <pthread.h> int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr); int pthread_mutex_destroy(pthread_mutex_t *mutex); int pthread_mutex_lock(pthread_mutex_t *mutex); int pthread_mutex_trylock(pthread_mutex_t *mutex); int pthread_mutex_timedlock(pthread_mutex_t *restrict mutex, const struct timespec *restrict abstime); int pthread_mutex_unlock(pthread_mutex_t *mutex); pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; /* static initialization */
| Name | Description |
|---|---|
mutex |
The mutex to operate on. |
attr |
Attributes (type, process-shared, robust), or NULL for the default. |
abstime |
(timedlock) Absolute deadline according to CLOCK_REALTIME. |
Returns: 0 on success, otherwise an error number (not errno). trylock returns EBUSY if the mutex is held, timedlock returns ETIMEDOUT at the deadline, an error-checking mutex returns EDEADLK (relock by the owner) or EPERM (unlock by a non-owner).
Mutex types
| Type | Locking it twice from the same thread |
|---|---|
PTHREAD_MUTEX_NORMAL |
Deadlock, or undefined behavior |
PTHREAD_MUTEX_ERRORCHECK |
Fails with EDEADLK |
PTHREAD_MUTEX_RECURSIVE |
Allowed; needs the same number of unlocks |
PTHREAD_MUTEX_DEFAULT |
Same as normal, or implementation-defined (on glibc, normal) |
Usage notes
- Unlock exactly what you lock, on every path including early returns and error exits. A lock held when a thread returns blocks everyone else forever.
- Never unlock a mutex you do not own, never destroy a locked one, and never copy a
pthread_mutex_t. Initialize it once (statically or withinit) and share the original. - Deadlock: if thread 1 holds A and waits for B while thread 2 holds B and waits for A, both wait forever. The cure is a global lock order, as in the transfer example.
- Keep critical sections short. Do not call blocking functions (I/O, sleeping) while holding a lock if you can avoid it.
- Contention costs. A lock taken once per increment, as in the first example, is correct but slow; accumulate locally and merge once, or use atomics for single counters.
- A mutex protects data, not code: associate each mutex with the variables it guards and document it.
- Mutexes must not be used inside signal handlers.
- C11
mtx_tin threads.h is the standard equivalent (mtx_lock,mtx_unlock).
Related
- pthread_create, pthread_cond, stdatomic.h
- Tutorial: Threads