With the MT refactor, it became more and more clear that we need more primitives to write safer, and faster, concurrent and parallel programs in Crystal, beyond the Channel, Mutex and the recent WaitGroup from stdlib
A couple weeks ago I started experimenting with synchronization primitives for Crystal, and I just pushed a new shard: sync.
The shard is meant to design, evolve, test and refine the API, until we believe that they’re sound, and maybe consider to push them to stdlib. The shard allows to use the primitives today in your apps, so we can get feedback from real apps.
The shard provides these basic types:
Sync::SemaphoreSync::Mutex(see below for why)Sync::RWLockSync::ConditionVariable
It also features wrapping types, to wrap a global variable with a mutex or rwlock:
Sync::Exclusive(T)Sync::Shared(T).
Finally, it features one high level data structure:
Sync::Map(K, V)—inspired by thedashmapRust crate
Last but not least: they’re not just safe, they’re fast!
I ported the nsync algorithms for mutexes, rwlocks and condition variables (see The Fastest Mutexes) and that led to writing a very efficient alternative to Mutex from stdlib (see the charts in README).
Sync::Map(K, V) requires quite some memory, but its performance skyrockets compared to a Hash protected by a single Sync::RWLock.