On Thu, Feb 15, 2007 at 05:40:30AM +0900, Bharat Ruparel wrote:
> # Sample code from Programing Ruby, page 131
> $stderr.sync = $stdout.sync = true
>   Thread.abort_on_exception = true
>   threads = []
>   4.times do |number|
>     threads << Thread.new(number) do |i|
>       raise "Boom!" if i == 2
>       print "#{i}\n"
>     end
>   end
>   threads.each {|t| t.join }
[...]
> When I run the code in SCITE, I get the following output:
> 
> >ruby ex0318.rb
> ex0318.rb:7: Boom! (RuntimeError)
>   from ex0318.rb:6:in `initialize'
>   from ex0318.rb:6:in `new'
>   from ex0318.rb:6
>   from ex0318.rb:5:in `times'
>   from ex0318.rb:5
> >Exit code: 1

The example assumes that the threads will be executed serially, and those with
i=0,1 will terminate before the third one raises a RuntimeError.

However, when you set $stdout.sync = true  each time you  printf whatever
Ruby will try to schedule another thread. In the above example, the two first
threads run until  print "#{i}\n" and the third thread, which raises an
exception, is scheduled before the numbers are actually written to $stdout.

If you change the example so that the threads are rescheduled before the next
one is created, you'll get the expected output:

$ ruby
 $stderr.sync = $stdout.sync = true
 Thread.abort_on_exception = true
 threads = []
 4.times do |number|
   threads << Thread.new(number) do |i|
     raise "Boom!" if i == 2
     print "#{i}\n"
   end
   sleep 0.01
 end
 threads.each {|t| t.join }
^D
0
1
-:6: Boom! (RuntimeError)
	from -:5:in `initialize'
	from -:5:in `new'
	from -:5
	from -:4:in `times'
	from -:4

IO#sync does work the way it should, but the example is confusing.

-- 
Mauricio Fernandez  -   http://eigenclass.org   -  singular Ruby
                        ** Latest postings **
Ruby, SEX and STDs: infectious practices
  http://eigenclass.org/hiki.rb?ruby-warnings-SEX-and-stds
What's new in Ruby 1.9, Feb. 07 update
  http://eigenclass.org/hiki.rb?Changes-in-Ruby-1.9-update-6