Skip to content

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.


#include <pthread.h>

Prototype

int pthread_mutex_unlock(pthread_mutex_t *mutex);

Parameters

mutex

Pointer to a mutex currently owned by the calling thread.

Example:

pthread_mutex_t lock;

Return Value

Returns:

0

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

pthread_mutex_lock(&lock);

/* critical section */

pthread_mutex_unlock(&lock);

Behavior

Conceptually:

Acquire Mutex
Access Shared Data
Release Mutex

After the unlock operation:

Other Waiting Threads
May Acquire Mutex

Example

pthread_mutex_lock(&lock);

shared_counter++;

pthread_mutex_unlock(&lock);

Waiting Thread Example

Thread A:

pthread_mutex_lock(&lock);

/* critical section */

pthread_mutex_unlock(&lock);

Thread B:

pthread_mutex_lock(&lock);

/* blocks until Thread A unlocks */

pthread_mutex_unlock(&lock);

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:

pthread_mutex_unlock(&lock);

after processing the condition.


Common Mistake

Incorrect:

pthread_mutex_lock(&lock);

if (error)
    return;

The mutex remains locked.

Correct:

pthread_mutex_lock(&lock);

if (error) {
    pthread_mutex_unlock(&lock);
    return;
}

Common Mistake

Incorrect:

pthread_mutex_unlock(&lock);

shared_counter++;

Shared data is modified after leaving the protected critical section.

Correct:

shared_counter++;

pthread_mutex_unlock(&lock);

Synchronization Flow

lock()
Critical Section
unlock()

The lock and unlock pair defines the protected region.


Comparison

Mutex

Acquire
Exclusive Access
Release

RWLock

Reader Lock
Writer Lock
Reader/Writer Unlock

Provides read concurrency.


Condition Variable

Uses a mutex together with:

pthread_cond_wait()

to implement event-based synchronization.