Safely share a value T across fibers and execution contexts using a RWLock to control when the access to a value can be shared (read-only) or must be exclusive (replace or mutate the value).
For example:
require "sync/shared"
class Queue
@@running : Sync::Shared.new([] of Queue)
def self.on_started(queue)
@@running.lock(&.push(queue))
end
def self.on_stopped(queue)
@@running.lock(&.delete(queue))
end
def self.each(&)
@@running.shared do |list|
list.each { |queue| yield queue }
end
end
end Consider a Shared(T) if your workload mostly consists of immutable reads of the value, with only seldom writes or inner mutations of the value's inner state.
Locks in shared mode and returns the value.
Locks in exclusive mode and yields the value.
Locks in exclusive mode, yields the current value and eventually replaces the value with the one returned by the block.
Locks in exclusive mode and sets the value.
Locks in shared mode and yields the value.
Returns the value without any synchronization.
Sets the value without any synchronization.
Reference
Reference
Reference
Object
Object
Object
Locks in shared mode and returns the value. Unlocks before returning.
Always acquires the lock, so reading the value is synchronized in relation with the other methods. However, safely accessing the returned value entirely depends on the safety of T.
Prefer #shared(&.dup) or #shared(&.clone) to get a shallow or deep copy of the value instead.
WARNING Breaks the shared/exclusive guarantees since the returned value outlives the lock, the value can be accessed concurrently to the synchronized methods.
Locks in exclusive mode and yields the value. The lock is released before returning.
The value is owned in exclusive mode for the duration of the block, as such it can be safely mutated.
WARNING The value musn't be retained and accessed after the block has returned.
Locks in exclusive mode, yields the current value and eventually replaces the value with the one returned by the block. The lock is released before returning.
The current value is now owned: it can be safely retained and mutated even after the block returned.
WARNING The new value musn't be retained and accessed after the block has returned.
Returns the value without any synchronization.
WARNING Breaks the safety constraints! Should only be called after acquiring the exclusive lock.
Sets the value without any synchronization.
WARNING Breaks the safety constraints! Should only be called after acquiring the exclusive lock.
© 2012–2026 Manas Technology Solutions.
Licensed under the Apache License, Version 2.0.
https://crystal-lang.org/api/1.19.0/Sync/Shared.html