Mutexes in Crystal
Here’s the translated code and explanation in Crystal, formatted for Hugo:
In this example, we’ll explore how to use mutexes to safely access data across multiple fibers. This is useful for more complex state management than what atomic operations can provide.
Running the program shows that the counters are updated as expected:
In this Crystal version, we’ve made a few adjustments to match the language’s idioms:
We use
require "mutex"
to import the mutex functionality.The
Container
class is defined with instance variables@mu
and@counters
.The
inc
method uses thesynchronize
method of the mutex, which automatically handles locking and unlocking.We use fibers (Crystal’s lightweight concurrency primitive) instead of goroutines.
We use a
Channel
to synchronize the fibers, similar to howWaitGroup
is used in the original example.The
do_increment
function is defined at the top level and takes the container, name, count, and channel as parameters.We use
spawn
to create new fibers.
This example demonstrates how to use mutexes in Crystal to safely manage shared state across multiple concurrent fibers. The mutex ensures that only one fiber can access or modify the shared counters at a time, preventing race conditions.
Next, we’ll look at implementing this same state management task using only fibers and channels.