[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

threads and puts

Emil Sandin

8/16/2007 10:51:00 AM

Hi, can anyone explain why this script:

Thread.new do
3.times{
puts "hello"
}
end

Gives the folllowing output:
"hello"

I expect it to print "hello" three times, just as it would if I hadn't
put it inside a thread. Do I need to flush the output or something like
that?
--
Posted via http://www.ruby-....

3 Answers

Tom Werner

8/16/2007 5:44:00 PM

0

Emil Sandin wrote:
> Hi, can anyone explain why this script:
>
> Thread.new do
> 3.times{
> puts "hello"
> }
> end
>
> Gives the folllowing output:
> "hello"
>
> I expect it to print "hello" three times, just as it would if I hadn't
> put it inside a thread. Do I need to flush the output or something like
> that?
>

It's a bit surprising that it outputs anything at all! If the above is
your entire program, then when the program exits, the thread will be
killed. On my system, that means no output at all. In order to wait for
the thread to complete (before the program exits), you need to call
'join' on it like so:

t = Thread.new do
3.times{
puts "hello"
}
end

t.join

Hope this helps.

Tom

--
* Libraries:
Chronic (chronic.rubyforge.org)
God (god.rubyforge.org)
* Site:
rubyisawesome.com


Emil Sandin

8/16/2007 8:11:00 PM

0

Thank you all, this makes it all much more understandable!
--
Posted via http://www.ruby-....

Giles Bowkett

8/17/2007 4:38:00 AM

0

Just for perspective, on my system, this prints "hello" three times,
as (incorrectly) expected.

--
Giles Bowkett

Blog: http://gilesbowkett.bl...
Portfolio: http://www.gilesg...