Using channels to communicate data safely
If sharing variables between fibers is not the proper way to communicate between fibers, then what is? The answer is channels. A channel is a way to communicate between fibers without needing to worry about race conditions, locks, semaphores, or other special structures. Let's take a look at the following example:
input_channel = Channel(Int32).new output_channel = Channel(Int32).new spawn do output_channel.send input_channel.receive * 2 end input_channel.send 2 puts output_channel.receive
The preceding example creates two channels that contain the Int32
input and output values. Then it spawns a fiber that first receives a value from the input channel, doubles it, and sends it to the output channel. We then send the input channel an initial value of 2
, and, finally, print the result we receive back from the output channel. As mentioned in the previous section, the fiber itself does not execute when we spawn it,...