Channel Buffering in Ruby
Ruby doesn’t have built-in support for buffered channels like Go does. However, we can simulate similar behavior using a Thread-safe Queue. Here’s an example that demonstrates a concept similar to buffered channels in Ruby:
In this Ruby code:
We use a
Queue
from thethread
library, which provides thread-safe operations.We set a
max_size
of 2 to simulate a buffer of 2 elements.We create a sender thread that attempts to send two messages to the queue. If the queue is full (i.e., has 2 elements), it waits before sending.
We create a receiver thread that receives two messages from the queue.
The
sleep(1)
at the end gives time for all operations to complete before the program exits.
To run the program, save it to a file (e.g., buffered_queue.rb
) and use the ruby
command:
This example demonstrates a concept similar to buffered channels in Ruby. While it’s not exactly the same as Go’s buffered channels, it provides a way to buffer a limited number of values that can be sent without an immediate receiver.