Channel Directions in Crystal
Channel directions in Crystal can be specified using the Channel(T).send
and Channel(T).receive
types. This specificity increases the type-safety of the program.
To run the program:
In Crystal, channels are used for communication between fibers (lightweight threads). The Channel(T).send
and Channel(T).receive
types are used to specify the direction of the channel.
The ping
function takes a send-only channel (Channel(String).send
) and a message. It sends the message on the channel.
The pong
function takes a receive-only channel (Channel(String).receive
) and a send-only channel (Channel(String).send
). It receives a message from the first channel and sends it on the second channel.
In the main
function, we create two buffered channels with a capacity of 1. We then spawn two fibers: one for ping
and one for pong
. Finally, we print the message received from the pongs
channel.
Crystal’s channel system is similar to the one in the original example, allowing for safe concurrent communication between fibers.