Reputation: 2889
I have this code:
... ....
ping_thread = Thread.new {
loop do
sleep 2
ping
end
}
ping_thread.join
puts "TEST"
... ....
it executes the ping function but does not move on printing the "TEST" statement. The ping function has a simple "puts "PING"" statement inside of it. I want the ping_thread to run as a background thread.
Upvotes: 2
Views: 232
Reputation: 1378
Thread.new
will start your thread running in the background automatically, and Thread#join
will block until that thread finishes its job. So normally, joining the thread is the last thing you do, when the main execution thread is done doing its work.
Try the following code and see if it does what you want:
ping_thread = Thread.new {
loop do
sleep 2
puts "ping"
end
}
puts "TEST"
ping_thread.join
Note that if you don't join the thead in the end, it will die when the main execution thread completes its work, so that join is necessary.
Upvotes: 4