1

Given a file looks like below:

Thread.new {
  (1..10).each do |e| 
    `curl http://localhost/#{e}`
  end 
}

sleep 0.03
puts "--- done"

When running this file, I found the "child thread" exits when it only sent 4-5 HTTP requests.

My question is: is this because the "ruby intepreter" exited? (so all the ruby threads terminated?)

How could I keep the "child thread" running when the "main thread" terminated?

If I run this code in ruby webservers such as thin, puma, does this problem exist?

Thank you.

Kimmo Lehto
  • 5,910
  • 1
  • 23
  • 32
Siwei
  • 19,858
  • 7
  • 75
  • 95

1 Answers1

2

When the main thread exits, the process terminates and it stops all the other running threads. To avoid that, you can call Thread#join that waits for the other thread.

thread = Thread.new {
  (1..10).each do |e| 
    `curl http://localhost/#{e}`
  end 
}

thread.join

Webservers processes most probably won't exit, but they may finish serving a request before the thread ends fetching the URL. It may be better to use a background processing tool to handle that case.

mrzasa
  • 22,895
  • 11
  • 56
  • 94
  • In other language such as Java/PHP, do they act like Ruby? ( child thread terminated when the main thread exits ) – Siwei Aug 27 '19 at 07:10
  • Yes, I believe it's the default behaviour: https://stackoverflow.com/questions/11875956/when-the-main-thread-exits-do-other-threads-also-exit https://stackoverflow.com/questions/4691533/java-wait-for-thread-to-finish. You need to call `join` to wait for a thread. – mrzasa Aug 27 '19 at 07:13
  • yeah, sure! I found it seems that in Java, "child thread" will run when main thread terminates. in C/C++, it acts the same with Ruby. I am not sure. so I will give enough test when I have time. thank you very much! – Siwei Aug 27 '19 at 08:15