make specific objects into monitors. : Synchronization « Threads « Ruby






make specific objects into monitors.


require 'monitor' 
class Counter 
    attr_reader :count 

    def initialize 
        @count = 0 
    end 

    def tick 
        @count += 1 
    end 
end 


c = Counter.new 
c.extend(MonitorMixin) 

t1 = Thread.new { 10000.times { c.synchronize { c.tick } } } 
t2 = Thread.new { 10000.times { c.synchronize { c.tick } } } 


t1.join; t2.join 
c.count # 20000 

 








Related examples in the same category

1.Multithreads without synchronization
2.Controlling the Thread Scheduler
3.This is easy using monitors.
4.Use monitor to lock
5.Synchronizing Access to an Object