Channels in Crystal
# Channels are the pipes that connect concurrent fibers. You can send values
# into channels from one fiber and receive those values into another fiber.
# Create a new channel with Channel(String).new
# Channels are typed by the values they convey.
messages = Channel(String).new
# Send a value into a channel using the channel.send syntax.
# Here we send "ping" to the messages channel we made above, from a new fiber.
spawn do
messages.send("ping")
end
# The channel.receive syntax receives a value from the channel.
# Here we'll receive the "ping" message we sent above and print it out.
msg = messages.receive
puts msg
When we run the program, the “ping” message is successfully passed from one fiber to another via our channel.
$ crystal channels.cr
ping
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.