pthread_mutex_unlock()¶
Purpose¶
pthread_mutex_unlock() releases a mutex previously acquired by the calling thread.
Once the mutex is released, another waiting thread may acquire ownership and enter the protected critical section.
Header¶
Prototype¶
Parameters¶
mutex¶
Pointer to a mutex currently owned by the calling thread.
Example:
Return Value¶
Returns:
on success.
Otherwise returns a POSIX error code.
Common errors:
| Error | Description |
|---|---|
| EINVAL | Invalid mutex |
| EPERM | Current thread does not own the mutex |
Usage Pattern¶
Behavior¶
Conceptually:
After the unlock operation:
Example¶
Waiting Thread Example¶
Thread A:
Thread B:
Relationship to Condition Variables¶
A common pattern:
pthread_mutex_lock(&lock);
while (!data_ready)
pthread_cond_wait(&cond, &lock);
pthread_mutex_unlock(&lock);
pthread_cond_wait() temporarily releases the mutex while sleeping and automatically re-acquires it before returning.
The caller still performs the final:
after processing the condition.
Common Mistake¶
Incorrect:
The mutex remains locked.
Correct:
Common Mistake¶
Incorrect:
Shared data is modified after leaving the protected critical section.
Correct:
Synchronization Flow¶
The lock and unlock pair defines the protected region.
Comparison¶
Mutex¶
RWLock¶
Provides read concurrency.
Condition Variable¶
Uses a mutex together with:
to implement event-based synchronization.