views:

34

answers:

2

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?

+1  A: 

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.

cHao
Fair enough. For what I"m REALLY wanting it for it's equivalent to just spawn off a thread to do the work, and have the thread itself encapsulated in a loop. I was just confused that there was still things to do, but it was quitting.
Jenny
You kinda need to babysit threads a bit at exit time. Wait for them to exit before the program ends. Apparently Ruby does indeed have a "join" method made just for that. :)
cHao
+4  A: 
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.

Jason Noble
In order to accomplish what she's expecting, the join would need to be *after* the "goodbye" message.
cHao