This Crystal program demonstrates the use of fibers (Crystal’s lightweight concurrency primitive) and channels to manage shared state. Here’s a breakdown of what’s happening:
We define ReadOp and WriteOp structs to represent read and write operations.
We create channels for reads and writes, which will be used to communicate between fibers.
A single fiber owns the state (a hash in this case). It continuously listens for read or write requests on the respective channels and processes them.
We spawn 100 fibers that continuously perform read operations, and 10 fibers that perform write operations.
Each read or write operation is performed by sending a request through the appropriate channel and waiting for a response.
We let the program run for one second, then print out the total number of read and write operations performed.
To run this program, save it to a file (e.g., stateful_fibers.cr) and use the Crystal compiler:
The output will vary, but you should see that the program completes about 70,000-80,000 total operations in one second.
This fiber-based approach to state management can be particularly useful in scenarios involving multiple channels or when managing multiple mutexes would be error-prone. However, for simpler cases, Crystal also provides more traditional concurrency primitives like mutexes. Choose the approach that feels most natural and makes it easiest to reason about the correctness of your program.