Channel Synchronization in Ruby

Our example demonstrates how to synchronize execution across threads using a queue. In Ruby, we’ll use the Queue class from the thread library to achieve similar functionality.

require 'thread'

# This is the method we'll run in a separate thread. The
# 'done' queue will be used to notify another thread
# that this method's work is done.
def worker(done)
  print "working..."
  sleep(1)
  puts "done"

  # Add a value to the queue to notify that we're done.
  done.push(true)
end

# Start a worker thread, giving it the queue to
# notify on.
done = Queue.new
Thread.new { worker(done) }

# Block until we receive a notification from the
# worker on the queue.
done.pop

To run the program:

$ ruby channel_synchronization.rb
working...done

In this Ruby version, we use a Queue instead of a channel. The Queue class in Ruby is thread-safe and can be used for inter-thread communication, similar to channels in other languages.

We define a worker method that simulates some work by sleeping for a second. After the work is done, it pushes a value onto the done queue.

In the main part of the program, we create a new Queue called done. We then start a new thread that runs the worker method, passing it the done queue.

Finally, we call done.pop, which blocks until there’s a value in the queue. This effectively waits for the worker thread to finish its job.

If you removed the done.pop line from this program, the main thread would exit before the worker thread even started its work.

This example demonstrates a simple way to synchronize threads in Ruby. For more complex scenarios involving multiple threads, you might want to look into Ruby’s Thread::Mutex class or the concurrent-ruby gem, which provides more advanced concurrency tools.