Goroutines in Ruby

A goroutine is a lightweight thread of execution.

def f(from)
  3.times do |i|
    puts "#{from} : #{i}"
  end
end

Suppose we have a function call f(s). Here’s how we’d call that in the usual way, running it synchronously.

f("direct")

To invoke this function in a thread, use Thread.new { f(s) }. This new thread will execute concurrently with the calling one.

Thread.new { f("thread") }

You can also start a thread for an anonymous function call.

Thread.new do
  puts "going"
end

Our two function calls are running asynchronously in separate threads now. Wait for them to finish (for a more robust approach, use a Mutex or other synchronization primitives).

sleep 1
puts "done"

When we run this program, we see the output of the blocking call first, then the output of the two threads. The threads’ output may be interleaved, because threads are being run concurrently by the Ruby runtime.

$ ruby goroutines.rb
direct : 0
direct : 1
direct : 2
thread : 0
going
thread : 1
thread : 2
done