Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does exiting a Ruby thread kill my whole program?

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?

like image 728
Seanny123 Avatar asked Sep 04 '13 03:09

Seanny123


People also ask

What does exit() do in a thread?

Thread#exit() : exit() is a Thread class method which is used to terminates the thread and schedules another thread to be run.

How many threads can ruby handle?

The Ruby interpreter handles the management of the threads and only one or two native thread are created.

How do you kill a thread in Ruby?

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 .


1 Answers

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"
like image 94
falsetru Avatar answered Nov 15 '22 07:11

falsetru