From: Hugh Sasse Date: 2006-07-06T18:32:57+09:00 Subject: Re: thread mystery On Thu, 6 Jul 2006, ara.t.howard@noaa.gov wrote: > > any idea why this script slows downs drastically as it runs and seems to leak > memory? I'm not familiar with enough with sync to answer this I suspect, esp. the memory part, but.... > > > require 'sync' > > class Switch > ON, OFF, NEITHER = true, false, nil > ...in here: > def initialize state = OFF > extend Sync_m > @state = NEITHER > @observers = [] > end state is not used. Should that be @state = state otherwise the default OFF doesn't agree with @state being set to NEITHER. > > def on! > synchronize(:EX){ > warn 'on!' > @state = ON > notity_observers > } > end > > def off! > synchronize(:EX){ > warn 'off!' > @state = OFF > notity_observers > } > end so both on! and off! notify_observers, however many.... > > def notity_observers > synchronize(:SH){ > @observers.each do |o| > o.notify @state > end > } > end so could you have a thread for each observer? > > def add_observer o > synchronize(:EX){ > @observers << o > } > end > end > > class SwitchToggle > def initialize switch > @switch = switch > @switch.add_observer self > end > def notify of > case of > when Switch::ON > Thread.new{ @switch.off! } > when Switch::OFF > Thread.new{ @switch.on! } > else > raise of.to_s > end > end > end > > switch = Switch.new > toggle = SwitchToggle.new switch > > switch.on! Not sure what happens when the synchronize is called within itself, because synchronize calls notity_observers which calls @switch.on! which calls synchronize which calls notity_observers.... Not spend enough time to really grok this though. > > STDIN.gets > Hugh