class Sync::RWLock

Overview

A multiple readers and exclusive writer lock to protect critical sections.

Multiple fibers can acquire the shared lock (read) to allow some critical sections to run concurrently. However a single fiber can acquire the exclusive lock at a time to protect a single critical section to ever run in parallel. When the lock has been acquired in exclusive mode, no other fiber can lock it, be it in shared or exclusive mode.

For example, the shared mode can allow to read one or many resources, albeit the resources must be safe to be accessed in such manner, while the exclusive mode allows to safely replace or mutate the resources with the guarantee that nothing else is accessing said resources.

The implementation doesn't favor readers or writers in particular.

NOTE Consider Shared(T) to protect a value T with a RWLock.

Included Modules

Defined in:

rw_lock.cr

Constructors

Instance Method Summary

Constructor Detail

def self.new(type : Type = :checked) #

[View source]

Instance Method Detail

def lock_read : Nil #

Acquires the shared (read) lock.

The shared lock is always reentrant, multiple fibers can lock it multiple times each, and never checked. Blocks the calling fiber while the exclusive (write) lock is held.


[View source]
def lock_write : Nil #

Acquires the exclusive (write) lock. Blocks the calling fiber while the shared or exclusive (write) lock is held.


[View source]
def read(& : -> U) : U forall U #

Acquires the shared (read) lock for the duration of the block.

Multiple fibers can acquire the shared (read) lock at the same time. The block will never run concurrently to an exclusive (write) lock.


[View source]
def try_lock_read? : Bool #

Tries to acquire the shared (read) lock without blocking. Returns true when acquired, otherwise returns false immediately.


[View source]
def try_lock_write? : Bool #

Tries to acquire the exclusive (write) lock without blocking. Returns true when acquired, otherwise returns false immediately.


[View source]
def unlock_read : Nil #

Releases the shared (read) lock.

Every fiber that locked must unlock to actually release the reader lock (so a writer can lock). If a fiber locked multiple times (reentrant behavior) then it must unlock that many times.


[View source]
def unlock_write : Nil #

Releases the exclusive (write) lock.


[View source]
def write(& : -> U) : U forall U #

Acquires the exclusive (write) lock for the duration of the block.

Only one fiber can acquire the exclusive (write) lock at the same time. The block will never run concurrently to a shared (read) lock or another exclusive (write) lock.


[View source]