简体   繁体   中英

Trying to understand Threading in Ruby. Test Code doesn't work as expected, why?

So, I wrote a quick thread example for myself, using the ruby docs for thread:

puts "Hello World"
test = Thread.new do
while true
  puts Time.now
end
end
puts "Goodbye World"

I would EXPECT this code to run forever, printing "Hello World", a few time stamps, goodbye world, and then a whole bunch of time stamps, until I manually break the code.

Instead, what I get is something like:

Hello World
Fri Aug 06 09:08:27 -0400 2010
Fri Aug 06 09:08:27 -0400 2010
Fri Aug 06 09:08:27 -0400 2010
Fri Aug 06 09:08:27 -0400 2010
Fri Aug 06 09:08:27 -0400 2010
Fri Aug 06 09:08:27 -0400 2010
Fri Aug 06 09:08:27 -0400 2010
Fri Aug 06 09:08:27 -0400 2010
Fri Aug 06 09:08:27 -0400 2010
Goodbye World

And then the program terminates. I'm REALLY confused here. Do threads terminate as soon as the next line of code would have started? Do they time out? I've tried adding

sleep 1

before and after the puts statement...but that just means that the thread prints less time stamps (if the sleep is before the puts, it prints nothing, just hello and goodbye, if after, it prints exactly one time stamp before exiting).

I don't have the most threading experience...but this seems really unintuitive to me... Am I doing something wrong? Using threads incorrectly? Am I doing it right but am confused about what threads are/do?

puts "Hello World"
test = Thread.new do
  while true
    puts Time.now
  end
end   
puts "Goodbye World"         
test.join

Calling the .join method on an instance of Thread class will make the program stop and wait for that thread to complete.

Not sure about the Ruby-specific stuff. Apart from that, generally when the script ends, the program ends -- in many cases, all the threads get killed off before the interpreter exits.

Threads are just a way to do a couple of things at once -- you shouldn't count on them to keep your program alive, especially once the main thread (the one that started everything) dies. If you want to wait for a thread to finish, most languages have a "join" or "wait" function that'd let the thread finish. But once the main thread's done, all bets are off.

With that said, Ruby may decide to let threads run til they finish. Like i said, not sure about that, cause it's Ruby-specific. But from the look of things, it'd seem not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM