3.5. rwlock — Reader-writer lock

An RW lock allows concurrent access for read-only operations, while write operations require exclusive access. This means that multiple threads can read the data in parallel but an exclusive lock is needed for writing or modifying data. When a writer is writing the data, all other writers or readers will be blocked until the writer is finished writing. A common use might be to control access to a data structure in memory that cannot be updated atomically and is invalid (and should not be read by another thread) until the update is complete.


Source code: src/sync/rwlock.h, src/sync/rwlock.c

Test code: tst/sync/rwlock/main.c

Test coverage: src/sync/rwlock.c


Functions

int rwlock_module_init(void)

Initialize the reader-writer lock module. This function must be called before calling any other function in this module.

The module will only be initialized once even if this function is called multiple times.

Return
zero(0) or negative error code

int rwlock_init(struct rwlock_t *self_p)

Initialize given reader-writer lock object.

Return
zero(0) or negative error code.
Parameters
  • self_p: Reader-writer lock to initialize.

int rwlock_reader_take(struct rwlock_t *self_p)

Take given reader-writer lock. Multiple threads can have the reader lock at the same time.

Return
zero(0) or negative error code.
Parameters
  • self_p: Reader-writer lock to take.

int rwlock_reader_give(struct rwlock_t *self_p)

Give given reader-writer lock.

Return
zero(0) or negative error code.
Parameters
  • self_p: Reader-writer lock give.

int rwlock_reader_give_isr(struct rwlock_t *self_p)

Give given reader-writer lock from isr or with the system lock taken.

Return
zero(0) or negative error code.
Parameters
  • self_p: Reader-writer lock to give.

int rwlock_writer_take(struct rwlock_t *self_p)

Take given reader-writer lock as a writer. Only one thread can have the lock at a time, including both readers and writers.

Return
zero(0) or negative error code.
Parameters
  • self_p: Reader-writer lock to take.

int rwlock_writer_give(struct rwlock_t *self_p)

Give given reader-writer lock.

Return
zero(0) or negative error code.
Parameters
  • self_p: Reader-writer lock to give.

int rwlock_writer_give_isr(struct rwlock_t *self_p)

Give given reader-writer lock from isr or with the system lock taken.

Return
zero(0) or negative error code.
Parameters
  • self_p: Reader-writer lock to give.

struct rwlock_t
#include <rwlock.h>

Public Members

int number_of_readers
int number_of_writers
volatile struct rwlock_elem_t *readers_p
volatile struct rwlock_elem_t *writers_p