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:
require 'thread'
# Create a Queue that can hold up to 2 messages
messages = Queue.new
max_size = 2
# Simulate sending messages to a buffered channel
Thread.new do
["buffered", "channel"].each do |message|
# Wait if the queue is full
sleep(0.1) while messages.size >= max_size
messages << message
puts "Sent: #{message}"
end
end
# Simulate receiving messages from a buffered channel
Thread.new do
2.times do
message = messages.pop
puts "Received: #{message}"
end
end
# Wait for all operations to complete
sleep(1)
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:
$ ruby buffered_queue.rb
Sent: buffered
Sent: channel
Received: buffered
Received: channel
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.