Weird behaviour of Ruby multithreading

Viewed 43

I'm trying to understand Ruby multithreading, and it seems just chaotic. Here's a couple examples I tried:

  1. Thread never gets executed and program ends
Thread.new do
  puts "thread"
end

puts "main"
  1. Thread is executed but never terminates
thread = Thread.new do
  puts "thread"
end

sleep while thread.alive?

puts "main"
  1. Everything unexpectedly works as expected:
thread = Thread.new do
  puts "thread"
end

puts thread.status while thread.alive?

puts "main"

What in Matz' name is going on here?!

1 Answers

Thread never gets executed and program ends

Thread.new do
  puts "thread"
end

puts "main"

Threads run in parallel. The main Ruby process will not automatically wait until all threads are completed before exiting.

What you're missing is join. This waits until the thread is done.

thread = Thread.new do
  puts "thread"
end

puts "main"

thread.join

Thread is executed but never terminates

thread = Thread.new do
  puts "thread"
end

sleep while thread.alive?

puts "main"

sleep with no arguments sleeps forever. Give it a short time to sleep and it works.

thread = Thread.new do
  puts "thread"
end

sleep(0.1) while thread.alive?

puts "main"

Everything unexpectedly works as expected:

thread = Thread.new do
  puts "thread"
end

puts thread.status while thread.alive?

puts "main"

Now that you're not sleeping forever, it works as expected.

Related