Channels in Crystal
When we run the program, the “ping” message is successfully passed from one fiber to another via our channel.
By default, sends and receives block until both the sender and receiver are ready. This property allowed us to wait at the end of our program for the “ping” message without having to use any other synchronization.
In Crystal, we use fibers for lightweight concurrency, which are similar to goroutines in concept. The spawn
keyword is used to create a new fiber, analogous to using go
in Go.
Channels in Crystal work similarly to those in Go, providing a way for fibers to communicate and synchronize. The Channel(T).new
syntax creates a new channel of type T, and channel.send
and channel.receive
are used for sending and receiving values, respectively.
This example demonstrates basic channel usage in Crystal, showing how to create channels, send values into them from one fiber, and receive those values in another fiber.