thread example

R

Ruby Newbee

Hello,

Just copied the code piece from the ruby cookbook:

require 'thread'
class CounterThread < Thread
def initialize
@count = 0
@continue = true
super do
@count += 1 while @continue
puts "I counted up to #{@count} before I was cruelly stopped."
end
end

def stop
@continue = false
end
end

counter = CounterThread.new
sleep 2
counter.stop


After I run it, I didn's see any output, even the expected puts:
"I counted up to #{@count} before I was cruelly stopped."

Where is wrong?
Thanks.
 
J

Jacob Mitchell

[Note: parts of this message were removed to make it a legal post.]

After I run it, I didn's see any output, even the expected puts:
"I counted up to #{@count} before I was cruelly stopped."

Where is wrong?
Thanks.
The output is getting buffered so it's just not getting displayed before the
thread stops. To fix this, put "$stdout.flush" at the end of your code.
 
R

Ruby Newbee

I would rather add "counter.join" at the end because otherwise process
may exit before the thread had time to generate the output. =C2=A0In that
case sync =3D true does not help much.

That's right.
we need a thread_object.join at the end.
Thanks robert.
 

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

Members online

No members online now.

Forum statistics

Threads
474,262
Messages
2,571,048
Members
48,769
Latest member
Clifft

Latest Threads

Top