sync
Sync
Synchronization primitives to build concurrent-safe and parallel-safe data structures in Crystal, so we can embrace MT with more serenity.
The provided sync primitives are meant to be useful yet low level. They can, and should, be used to protect simple resources, but also to build higher level constructs, for example an actor library.
The underlying implementation follows the nsync algorithm, that was easy to adapt from threads to fibers. Compared to a naive atomic+spinlock mutex, the algorithm is incredibly fast and efficient (much less wasted CPU time), and it eventually reaches a stable value, whatever how many fibers you put, while the naive implementation quickly goes exponential).
Status
Experimental: in progress work to flesh out sync primitives that we may want to have in Crystal's stdlib at some point.
Documentation
Run make docs or head to CrystalDoc.info.
Primitives
- 
Sync::Safeto annotate types as (a)sync safe. - 
Sync::Lockableto abstract the different locks (internal). - 
Sync::Mutexto protect critical sections using mutual exclusion. - 
Sync::RWLockto protect critical sections using shared access and mutual exclusion. - 
Sync::ConditionVariableto synchronize critical sections together. - 
Sync::Exclusive(T)to protect a valueTusing mutual exclusion. - 
Sync::Shared(T)to protect a valueTusing a mix of shared access and mutual exclusion. - 
Sync::Future(T)to delegate the computation of a valueTto another fiber. - 
Sync::Map(K, V)for a distributed hash-like data structure. 
TODO
-  
Sync::Semaphore(?) 
Performance
While the performance of Mutex in stdlib is very performant when uncontended or with only a couple threads (MT:2), the nsync algorithm used by Sync::Mutex quickly proves much more performant and efficient, it even reaches expected performance and efficiency (whatever the number of fibers), while  Mutex performance drops, and efficiency plummets (high CPU time).
Here are the results of running bench/mutex.cr in a multithreaded execution context (28 threads) on an Intel 14700K.
License
Distributed under the Apache-2.0 license. Use at your own risk.
sync
- 25
 - 0
 - 11
 - 1
 - 1
 - 3 days ago
 - May 11, 2025
 
Apache License 2.0
Mon, 03 Nov 2025 09:08:50 GMT