Skip to content

pthread_rwlock_unlock()

Purpose

pthread_rwlock_unlock() releases a previously acquired reader or writer lock.

The function is used to leave a reader-writer critical section and allow other waiting readers or writers to proceed.


#include <pthread.h>

Prototype

int pthread_rwlock_unlock(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
EINVAL Invalid rwlock object
EPERM Current thread does not own the lock

Usage Pattern

Reader

pthread_rwlock_rdlock(&lock);

/* read shared data */

pthread_rwlock_unlock(&lock);

Writer

pthread_rwlock_wrlock(&lock);

/* modify shared data */

pthread_rwlock_unlock(&lock);

Reader Release

Conceptually:

Reader Enter
Read Data
Reader Exit

The reader count maintained by the implementation is decremented.

When the last reader exits:

Reader Count
1 → 0

waiting writers may proceed.


Writer Release

Conceptually:

Writer Enter
Modify Data
Writer Exit

Exclusive ownership is released.

Waiting readers or writers may acquire the lock.


Example

Reader:

pthread_rwlock_rdlock(&lock);

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

pthread_rwlock_unlock(&lock);

Writer:

pthread_rwlock_wrlock(&lock);

shared_value++;

pthread_rwlock_unlock(&lock);

Synchronization Flow

Reader Side

rdlock()
Access Shared Data
unlock()

Writer Side

wrlock()
Modify Shared Data
unlock()

Common Mistake

Incorrect:

pthread_rwlock_rdlock(&lock);

if (error)
    return;

The lock is never released.

Correct:

pthread_rwlock_rdlock(&lock);

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

Common Mistake

Incorrect:

pthread_rwlock_wrlock(&lock);

pthread_rwlock_unlock(&lock);

shared_value++;

Shared data is modified after the lock has been released.

Correct:

pthread_rwlock_wrlock(&lock);

shared_value++;

pthread_rwlock_unlock(&lock);

Relationship to Fairness

Releasing a lock may wake:

Waiting Readers

or:

Waiting Writers

depending on the implementation's fairness policy.

Examples:

Reader Preference
Writer Preference
Fair Policy

Different implementations may choose different wake-up behavior.


Comparison

Mutex

pthread_mutex_unlock()

Releases exclusive ownership.


RWLock

pthread_rwlock_unlock()

Releases either:

Reader Ownership

or:

Writer Ownership

depending on how the lock was acquired.