From: ara.t.howard@... Date: 2007-01-04T13:12:38+09:00 Subject: Re: Problem in Unit Testing Methods that start new threads On Thu, 4 Jan 2007, Hemant Kumar wrote: > > Since We are calling new each time, even using instance variables won't > solve the race condition. I have even tried using class variables, and I am > still getting race condition. > > Ara, please demonstrate how you would solve the race condition in above > shown code of yours? > hi hemant- without thinking too hard about it i'd probably do something like this: harp:~ > cat a.rb require 'sync' require 'thread' class Module def tattr a module_eval <<-code def #{ a }= arg synchronize(:EX){ @#{ a } = arg } end def #{ a } synchronize(:SH){ @#{ a } } end code end end class C include Sync_m tattr :thread def initialize @thread = nil sync_initialize end def new_thread q = Queue.new Thread.new{ q.push( self.thread = Thread.current ) } ensure q.pop end end 4242.times{|i| raise "race @ loop #{ i } condition!" unless((c = C.new) and (Thread === c.new_thread) and c.thread) } p 42 harp:~ > ruby a.rb 42 harp:~ > ruby a.rb 42 harp:~ > ruby a.rb 42 harp:~ > ruby a.rb 42 the methodology of waiting for the 'q.push' is useful so your method only returns after the thread has 'started' running. kind regards. -a -- if you find yourself slandering anybody, first imagine that your mouth is filled with excrement. it will break you of the habit quickly enough. - the dalai lama