From: Edgardo Hames Date: 2004-05-08T03:45:17+09:00 Subject: Re: signaling another thread 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, which you cannot do if you where using a Condition Variable. A Condition Variable could be used to guarantee exclusive access to @i. 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