Skip to content

down_read() / up_read() / down_write() / up_write()

Purpose

Provides reader-writer synchronization for shared kernel data.

Multiple readers may access the protected resource concurrently, while writers require exclusive access.

#include <linux/rwsem.h>

Prototype

void down_read(struct rw_semaphore *sem);
void up_read(struct rw_semaphore *sem);

void down_write(struct rw_semaphore *sem);
void up_write(struct rw_semaphore *sem);

Parameters

  • sem: Pointer to an initialized struct rw_semaphore.

Return Value

These functions do not return a value.

Reader and writer contexts may sleep while waiting for the semaphore.

Execution Context

Reader-writer semaphores are sleepable synchronization primitives.

Typical usage includes:

  • Process Context
  • Workqueues
  • Kernel threads
  • Threaded IRQ handlers

Reader-writer semaphores must never be used inside hard IRQ handlers.

Minimal Example

/* Reader */
down_read(&dev->rwsem);

/* Read shared data */

up_read(&dev->rwsem);
/* Writer */
down_write(&dev->rwsem);

/* Update shared data */

up_write(&dev->rwsem);

Common Pitfalls

  • Do not use reader-writer semaphores in hard IRQ context.
  • Prefer a mutex when read and write operations occur with similar frequency.
  • Reader-writer semaphores are most beneficial for read-heavy workloads.