From: Robert Klemme Date: 2004-05-08T07:58:56+09:00 Subject: Re: signaling another thread "Edgardo Hames" schrieb im Newsbeitrag news:409BD97D.8060805@vates.com... > Robert Klemme wrote: > > > That code is not thread safe. At least @i is accessed unsychronized. > > While it *may* work it is unsafe. > > I know it is unsafe. I just wanted to write an example on how a thread > could be working and stop when a certain event was notified, Your thread does neither stop nor is it interrupted. WarnLow#m just does an endless loop and increments @i without taking any notice of #update calls. It is the same instance but a different thread context. You can view that easily by including the current thread in your printout like class WarnHigh < Warner def update(time, price) # callback for observer if price > @limit print "#{Thread.current.inspect}: +++ #{time}: Price above #@limit: #{price}\n" end end end You'll notice that it is the same as the main program, which happens to execute Ticker#run > which you > cannot do if you where using a Condition Variable. That's right: with a condition variable the thread is suspended and does nothing. > A Condition Variable > could be used to guarantee exclusive access to @i. For exclusive access a mutex is sufficient. The condition variable buys you the added convenience that a thread is suspended while waiting for a condition change (technically for a signal to occur). robert > 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 > > >