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?