6
votes

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?

1

1 Answers

9
votes

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"