Skip to content

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.


#include <pthread.h>

Prototype

int pthread_mutex_lock(pthread_mutex_t *mutex);

Parameters

mutex

Pointer to an initialized mutex.

Example:

pthread_mutex_t lock;

Return Value

Returns:

0

on success.

Otherwise returns a POSIX error code.

Common errors:

Error Description
EINVAL Invalid mutex
EDEADLK Deadlock detected

Usage Pattern

pthread_mutex_lock(&lock);

/* access shared data */

pthread_mutex_unlock(&lock);

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

pthread_mutex_lock(&lock);

shared_counter++;

pthread_mutex_unlock(&lock);

Typical Use Cases

Shared Variables

Configuration state
Device state
Counters

Shared Data Structures

Linked lists
Queues
Trees
Hash tables

Condition Variables

Mutexes are commonly paired with:

pthread_cond_wait()

Example:

pthread_mutex_lock(&lock);

while (!data_ready)
    pthread_cond_wait(&cond, &lock);

pthread_mutex_unlock(&lock);

Why Mutual Exclusion Is Needed

Without synchronization:

Thread-A reads value
Thread-B reads value
Thread-A updates value
Thread-B updates value

Updates may be lost.

Mutexes serialize access:

Thread-A
Critical Section
Thread-B

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.


Comparison

Mutex

One Owner

RWLock

Multiple Readers
One Writer

Seqlock

Lockless Readers
Retry Possible

RCU

Lockless Readers
Object Lifetime Management