Skip to content

pthread_rwlock_wrlock()

Purpose

pthread_rwlock_wrlock() acquires a write lock on a POSIX reader-writer lock.

The write lock provides exclusive access to the protected data.

While a writer holds the lock:

  • No readers may acquire the lock.
  • No other writers may acquire the lock.

#include <pthread.h>

Prototype

int pthread_rwlock_wrlock(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_wrlock(&lock);

/* modify shared data */

pthread_rwlock_unlock(&lock);

Writer Behavior

A writer requires exclusive ownership.

Example:

Reader-1 Active
Reader-2 Active
Reader-3 Active
Writer Waits

The writer cannot proceed until all readers leave the critical section.


Blocking Behavior

A writer blocks when:

Readers Active

or:

Another Writer Active

Example

pthread_rwlock_wrlock(&lock);

shared_value++;

pthread_rwlock_unlock(&lock);

Typical Use Cases

Configuration Updates

Many readers
Occasional updates

Shared Lookup Tables

Readers access frequently
Writers update infrequently

Dynamic Data Structures

Linked list
Tree
Hash table

where modifications require exclusive access.


Writer Fairness

RWLock implementations must decide how to handle waiting writers.

Common policies:

Reader Preference

New Readers Allowed
While Writer Waiting

Advantages:

Maximum Reader Throughput

Disadvantages:

Writer Starvation Possible

Writer Preference

Block New Readers
When Writer Waiting

Advantages:

Writer Eventually Progresses

Disadvantages:

Reader Latency Increases

Relationship to Day62

The Day62 lab explored:

Reader Preference
Writer Preference
Fairness Policies
Starvation Behavior

using custom reader-writer lock implementations.


Advantages

Higher Read Concurrency

Multiple readers can execute simultaneously.


Exclusive Writer Access

Writers can safely modify shared data.


Limitations

Writer May Wait For All Readers

A long-running reader delays writers.


More Complex Than Mutex

RWLock introduces fairness and starvation considerations.


Reader Overhead Still Exists

Readers still acquire and release locks.

This motivates lockless-read mechanisms such as:

Seqlock
RCU

Comparison

Mutex

One Reader Or One Writer

RWLock

Multiple Readers
Or
One Writer

Seqlock

Readers do not acquire locks but may retry.


RCU

Readers do not acquire locks and focus on safe object lifetime management.