Skip to main content Link Menu Expand (external link) Document Search Copy Copied

Readers-writers locks

In the starter code, we provide you with a working implementation of a readers-writers lock, should you choose to use it. The API for the lock is defined in threads/synch.h, and is shown below for convenience.

/* Readers-writers lock. */
#define RW_READER 1
#define RW_WRITER 0

struct rw_lock {
  struct lock lock;
  struct condition read, write;
  int AR, WR, AW, WW;

void rw_lock_init(struct rw_lock*);
void rw_lock_acquire(struct rw_lock*, bool reader);
void rw_lock_release(struct rw_lock*, bool reader);

You can initialize a readers-writers lock with the rw_lock_init function, which mirrors the standard lock_init function. Unlike a standard lock, you may acquire a readers-writers lock in either reader mode or writer mode, which is specified by bool reader.. You can use the definitions of RW_READER and RW_WRITER for cleaner code. One example usage (for a readers lock on the stack) is shown below:

void demo_rw_lock_function() {
    // Allocate bytes for rw_lock on the stack
    struct rw_lock my_rw_lock;

    // Initialize the RW lock
    // Acquire RW lock in reader mode
    rw_lock_acquire(&rw_lock, RW_READER);
    // Release RW lock in reader mode
    rw_lock_release(&rw_lock, RW_READER);