threads and puts

E

Emil Sandin

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?
 
T

Tom Werner

Emil said:
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
 
G

Giles Bowkett

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

puts and return 13
Creating and Executing New Threads 4
Puts return 6
"puts"ing an array 6
puts box.dup.enlarge(4, 5) -- unexpected result 2
Threads 1
question on threads 3
A problem with "puts" 2

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,679
Members
48,796
Latest member
Greg L.

Latest Threads

Top