Channels in Ruby
In Ruby, we can use threads and queues to achieve similar functionality to Go’s channels. Here’s an example that demonstrates the concept:
require 'thread'
# Create a new queue to act as our channel
messages = Queue.new
# Send a value into the queue using a new thread
Thread.new do
messages.push("ping")
end
# Receive the value from the queue and print it
msg = messages.pop
puts msg
In this example, we’re using Ruby’s Queue
class to simulate a channel. The Queue
class provides thread-safe operations for passing messages between threads.
We create a new queue called messages
using Queue.new
. This queue will act as our channel for passing messages between threads.
To send a value into the queue, we create a new thread using Thread.new
. Inside this thread, we use the push
method to add the string “ping” to the queue. This is similar to sending a value into a channel in Go.
To receive a value from the queue, we use the pop
method. This method will block until a value is available in the queue, similar to receiving from a channel in Go. We store the received value in the msg
variable and then print it.
When we run this program, the “ping” message is successfully passed from one thread to another via our queue.
$ ruby channels.rb
ping
By default, the pop
method blocks until a value is available in the queue. This property allowed us to wait at the end of our program for the “ping” message without having to use any other synchronization mechanism.
While Ruby’s threads and queues don’t provide exactly the same semantics as Go’s goroutines and channels, they can be used to achieve similar patterns of concurrent communication and synchronization.