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.
On Thu, Jan 21, 2010 at 10:53 PM, Ruby N. [email protected]
wrote:
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.
2010/1/22 Jacob M. [email protected]:
thread stops. To fix this, put “$stdout.flush” at the end of your code.
I would rather add “counter.join” at the end because otherwise process
may exit before the thread had time to generate the output. In that
case sync = true does not help much.
Kind regards
robert
On Fri, Jan 22, 2010 at 4:20 PM, Robert K.
[email protected] wrote:
I would rather add “counter.join” at the end because otherwise process
may exit before the thread had time to generate the output. Â In that
case sync = true does not help much.
That’s right.
we need a thread_object.join at the end.
Thanks robert.