j
jaipkg.dev
packages / library / rw-mutex

rw-mutex

v1.0.0library

Jai read-write mutex

MIT · updated 6 months ago

rw-mutex

This is a read-write mutex with writer-preference module for Jai.

Many readers can be active at once, but once a writer comes and starts waiting it blocks all new readers. Once the ongoing readers finish, the writer(s) are given the lock, one writer at a time, until we have zero pending writers.

Once all pending/active writers finish, readers are allowed again.

Note: a constant stream of writers without any breaks will starve readers.

Usage

#import "Basic";

// Assuming Rw_Mutex.jai is inside your 'modules' folder
#import "Rw_Mutex";

main :: () {
    shared_value: int = 0;
    rwm := rwm_new("example mutex");
    defer rwm_free(*rwm);

    // Multiple readers can be active at once
    rwm_rlock(*rwm);
    print("Read: Shared value is %\n", shared_value);

    rwm_rlock(*rwm);
    print("Another read: Shared value is %\n", shared_value);

    // In a multi-threaded environment, this will block until all current readers unlock, and will block any
    // new readers trying to take a read lock.
    // rwm_wlock(*rwm);

    // All readers must unlock before a writer can acquire the lock
    rwm_runlock(*rwm);
    rwm_runlock(*rwm);

    // Write operation
    rwm_wlock(*rwm);
    shared_value += 1;
    print("Write: Updated shared value to %\n", shared_value);
    rwm_wunlock(*rwm);

    // Another read after write
    rwm_rlock(*rwm);
    print("Read after write: Shared value is %\n", shared_value);
    rwm_runlock(*rwm);

    // Another write
    rwm_wlock(*rwm);
    shared_value += 1;
    print("Another write: Updated shared value to %\n", shared_value);
    rwm_wunlock(*rwm);

    print("Done!\n");
}