Mike Glaz
Mike Glaz

Reputation: 5382

Ruby Threads output

I am reading David A. Black's The Well-Grounded Rubyist, 3rd Edition.

In the section on threads, the author's output of the following code snippet differs from what appears on my system (section 14.5).

Thread.new do
  puts "Starting the thread"
  sleep 1
  puts "At the end of the thread"
end
puts "Outside the thread"

Author's output:

Starting the thread
Outside the thread

My output is only:

Outside the thread

The author then sets the code block to variable t and calls t.join which gives him the following output:

Starting the thread
Outside the thread
At the end of the thread

However, my output is:

Outside the thread
Starting the thread
At the end of the thread

Am I missing something?

I am using ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-linux-gnu]

Upvotes: 1

Views: 59

Answers (1)

Pan Ke
Pan Ke

Reputation: 579

Because main thread continue doing the job before the spawned thread starts.

1, try to put a sleep 0.1 before puts "Outside the thread"

Thread.new do
  puts "Starting the thread"
  sleep 1
  puts "At the end of the thread"
end
sleep 0.1 #let spawned thread start
puts "Outside the thread"
  1. join before puts "Outside the thread"
Thread.new do
  puts "Starting the thread"
  sleep 1
  puts "At the end of the thread"
end.join # wait spawned thread finish
puts "Outside the thread"

Upvotes: 1

Related Questions