Skip to content

pthread_rwlock_rdlock()

Purpose

pthread_rwlock_rdlock() acquires a read lock on a POSIX reader-writer lock.

Multiple readers may hold the lock simultaneously, provided no writer currently owns the lock.

This allows concurrent read access to shared data.


#include <pthread.h>

Prototype

int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock);

Parameters

rwlock

Pointer to an initialized reader-writer lock.

Example:

pthread_rwlock_t lock;

Return Value

Returns:

0

on success.

Otherwise returns a POSIX error code.

Common errors:

Error Description
EDEADLK Deadlock detected
EINVAL Invalid rwlock object

Usage Pattern

pthread_rwlock_rdlock(&lock);

/* read shared data */

pthread_rwlock_unlock(&lock);

Reader Behavior

Multiple readers may enter simultaneously:

Reader-1
Reader-2
Reader-3

All can acquire:

pthread_rwlock_rdlock()

at the same time.


Blocking Behavior

Readers block when:

Writer Holds Lock

Example:

Writer Active
Reader Waits

until the writer releases the lock.


Example

pthread_rwlock_rdlock(&lock);

printf("value=%d\n", shared_value);

pthread_rwlock_unlock(&lock);

Typical Use Cases

Configuration Tables

Many readers
Rare updates

Lookup Tables

Routing tables
Device tables

Shared Read-Mostly Data

Read frequency
>>
Write frequency

Advantages

Concurrent Readers

Readers do not block each other.


Simple Programming Model

Very similar to mutex usage.


Limitations

Reader Locking Overhead

Readers still perform synchronization operations.

Every reader acquires and releases a lock.


Writer Starvation

Some implementations may allow continuous readers to delay writers.

Fairness policy is implementation-dependent.


Comparison

Mutex

1 Reader

or

1 Writer

only.


RWLock

Multiple Readers

or

1 Writer

Seqlock

Readers avoid locking but may need retries.


RCU

Readers avoid locking and focus on object lifetime management.