Concurrency
Crystal Channels
Using Channels
Crystal channels allow fiber communication with Channel.
Introduction to Crystal Channels
In Crystal, channels are a powerful construct that facilitate communication between fibers. Channels allow you to send messages from one fiber to another, enabling concurrent operations and efficient data exchange. They are particularly useful in scenarios where you need to synchronize tasks or manage shared resources.
Creating a Channel
To create a channel in Crystal, you use the Channel
class. A channel can be instantiated with a specific type, which dictates what kind of data it can transmit. Here is a simple example:
In this example, channel
is configured to send and receive Int32
values. You can also create untyped channels by omitting the type, but using typed channels is generally recommended for type safety.
Sending and Receiving Messages
Once a channel is created, you can send and receive messages using the send
and receive
methods. Here's how you can do it:
In this example, a fiber is created using the go
keyword, which sends the integer 5
through the channel. The main fiber then receives this value and prints it to the console.
Buffered Channels
Channels in Crystal can be buffered or unbuffered. A buffered channel allows you to send multiple messages without requiring an immediate receive. You can create a buffered channel by specifying its capacity:
This channel can hold up to 10 messages before it blocks further sends. Buffered channels are helpful when you want to decouple the sending and receiving operations, allowing senders to proceed without waiting for receivers.
Select Statement
The select
statement in Crystal allows you to wait on multiple channel operations. This is useful when you need to handle multiple channels or possible operations simultaneously. Here is an example:
In this code, the select
block waits for a message from the channel
or a timeout of 2 seconds, whichever comes first. This approach allows for more responsive and flexible channel handling.
Closing a Channel
Closing a channel is an important operation that signals no more messages will be sent. It is done using the close
method:
After a channel is closed, any attempt to send a message will result in an error, but you can still receive remaining messages until the channel is empty.
Concurrency
- Fibers
- Channels
- Async Await
- Previous
- Fibers
- Next
- Async Await