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."
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
···
2010/1/22 Jacob Mitchell <jacob.d.mitchell@gmail.com>:
On Thu, Jan 21, 2010 at 10:53 PM, Ruby Newbee <rubynewbee@gmail.com> 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.
That's right.
we need a thread_object.join at the end.
Thanks robert.
···
On Fri, Jan 22, 2010 at 4:20 PM, Robert Klemme <shortcutter@googlemail.com> 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.