On 12.03.2010 04:01, Jean G. wrote:
> Hello,
> 
> $ cat count_threads.rb
> class Counter
>   attr_reader :count
>   def initialize
>     @count = 0
>   end
>   def tick
>     @count += 1
>   end
> end
> 
> c = Counter.new
> t1 = Thread.new { 10000.times { c.tick } }
> t2 = Thread.new { 10000.times { c.tick } }
> t1.join
> t2.join
> puts c.count
> 
> $ ruby count_threads.rb
> 20000
> $ ruby count_threads.rb
> 20000
> $ ruby count_threads.rb
> 20000
> 
> 
> 
> My ruby version is 1.9, running under Linux-2.6.31 kernel.
> For the code above, though we know the @count isn't safe for sharing.
> But the result is always correct.
> So can we say ruby-1.9 behaves better on threads than 1.8?

The test proves nothing other than that you got what seems like a proper 
sum in the end.  The runtime could have made accesses to @count atomic - 
or you could have been lucky (more likely).

It's actually the other way round: if the result would have been != 
20000 Ruby 1.9 could be said to behave better on threads than 1.8.  The 
reason is that this would tell you that there are actually concurrent 
accesses to the same memory, which means there would be more concurrency 
in 1.9 than in 1.8 with its green threads.

A system which guards accesses to shared resources *without* explicit 
synchronization would be very bad because it would sacrifice performance 
without reason.

Kind regards

	robert


-- 
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/