I have this piece of code:
puts "Start"
loop do
Thread.start do
puts "Hello from thread"
exit
end
text = gets
puts "#{text}"
end
puts "Done"
What I would expect is seeing "Start" followed by "Hello from thread" and then I could enter input that would get echoed back to me. Instead I get "Start" and "Hello from thread" and then the program exits.
From the documentation on exit
:
Terminates thr and schedules another thread to be run. If this thread is already marked to be killed, exit returns the Thread. If this is the main thread, or the last thread, exits the process.
But I thought I spawned a new thread? Why is it exiting my main process?
Thread#exit() : exit() is a Thread class method which is used to terminates the thread and schedules another thread to be run.
The Ruby interpreter handles the management of the threads and only one or two native thread are created.
For terminating threads, Ruby provides a variety of ways to do this. Alternatively, you can use the instance method exit , or any of its aliases kill or terminate .
You're looking at the Thread#exit
documentation. kill
is Kernel#exit
which terminates the Ruby script.
puts "Start"
loop do
Thread.start do
puts "Hello from thread"
Thread.exit
end
text = gets
puts "#{text}"
end
puts "Done"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With