From: Robert Klemme Date: 2004-05-08T00:58:56+09:00 Subject: Re: signaling another thread "Edgardo Hames" schrieb im Newsbeitrag news:409BAC91.4070902@vates.com... > Robert Klemme wrote: > > > >> I'd take the ConditionVariable approach if I could, otherwise I don't > >> see why you can't use the Observer Paradigm. Maybe, I'm missing the > >> point. > > > > Hm, dunno how exactly you want to treat this with observer. But you need > > some kind of thread synchronization anyway, even if you use observer. > > > > Are you familiar with multithreaded applications? > > > > Condition variables, semaphores and monitors grant you exclusive access > to shared resources. That means only one thread will access a resource > in a given moment. > > The Observer Paradigm, allows an object to be notified when a certain > event happens. Check the following heavily based on the example in "The > Pragmatic Programmer's Guide" :-). I added a method m to the WarnLow > Class that loops until it gets notified. That code is not thread safe. At least @i is accessed unsychronized. While it *may* work it is unsafe. Apart from that: all notifications occur in thread main, no thread really reacts on the status change. Normally you would have used a condition variable that was accessed from WarnLow#m and #update. Then you would not have the thread spinning around doing nothing and waisting resources (CPU cycles that is). But this seems to be only an example. It depends on the real problem at hand which approach is best. Regards robert > I hope it helps. > Ed > > ----8<--------8<--------8<--------8<---- > require "observer" > > > > > class Ticker > include Observable > def run > i = 0 > while (i < 130) > changed(i > 70) > notify_observers(Time.now, i) > i = i + 1 > end > end > end > > class Warner > def initialize(ticker, limit) > @limit = limit > ticker.add_observer(self) # all warners are observers > end > end > > > class WarnLow < Warner > def m > @i = 0 > loop do > @i = @i + 1 > end > end > def update(time, price) # callback for observer > if price < @limit > print "#@i #{time.to_s}: Price below #@limit: #{price}\n" > end > end > end > > > > > class WarnHigh < Warner > def update(time, price) # callback for observer > if price > @limit > print "+++ #{time.to_s}: Price above #@limit: #{price}\n" > end > end > end > > > > > ticker = Ticker.new() > Thread.new { > wl = WarnLow.new(ticker, 80) > wl.m > } > WarnHigh.new(ticker, 120) > ticker.run > > > > -- > Edgardo Hames > Consultor Inform�tico > Vates S.A. Ingenier�a de Software > > ehames@vates.com > Tel: +54 +351 +4240133 int. 121 > 9 de Julio 228 - 6� piso. C�rdoba > > >