pthread_mutex_lock()¶
Purpose¶
pthread_mutex_lock() acquires a mutex.
If another thread already owns the mutex, the calling thread blocks until the mutex becomes available.
Mutexes provide mutual exclusion and protect shared mutable state from concurrent access.
Header¶
Prototype¶
Parameters¶
mutex¶
Pointer to an initialized mutex.
Example:
Return Value¶
Returns:
on success.
Otherwise returns a POSIX error code.
Common errors:
| Error | Description |
|---|---|
| EINVAL | Invalid mutex |
| EDEADLK | Deadlock detected |
Usage Pattern¶
Behavior¶
Only one thread may own a mutex at a time.
Example:
Thread-A acquires mutex
↓
Thread-B attempts lock
↓
Thread-B blocks
↓
Thread-A unlocks
↓
Thread-B acquires mutex
Example¶
Typical Use Cases¶
Shared Variables¶
Shared Data Structures¶
Condition Variables¶
Mutexes are commonly paired with:
Example:
pthread_mutex_lock(&lock);
while (!data_ready)
pthread_cond_wait(&cond, &lock);
pthread_mutex_unlock(&lock);
Why Mutual Exclusion Is Needed¶
Without synchronization:
Updates may be lost.
Mutexes serialize access:
Advantages¶
Simple¶
Easy to understand and use.
Safe¶
Prevents concurrent modification of shared state.
Widely Supported¶
Available on virtually all POSIX systems.
Limitations¶
No Read Parallelism¶
Readers and writers are treated equally.
Only one thread may enter the critical section.
Blocking¶
Threads may sleep while waiting.
Potential Deadlocks¶
Incorrect lock ordering may lead to deadlock.