From: Robert Klemme Date: 2010-12-19T00:50:23+09:00 Subject: Re: background threads On 18.12.2010 15:10, Venkat Akkineni wrote: > Mike > > > Thanks for your reply. The flag is wrong indeed. I didn't notice > this because the 'else' part of setSignal never gets executed with the > current setup. You will notice that the program runs exactly the same > way even when all commands inside setSignal except call to > display function are commented. > > def setSignal(signal) > # if signal == true > display > # else > # self.aFlag=true > # end > end > > When I change the display function to the following > > def display > self.run > sleep 20 > end > > program prints 'I am here' after 20 seconds. > > The reason I did not have an argument for sleep is I wan't the thread > run indefinitely until I call it off some how. This is the desired > effect. > > Two approaches I have tried are > > 1.) loop through indefinitely around necessary code block. I am not sure what you mean. > 2.) create a thread around the above loop and call Thread.join. If you create a thread and then do nothing but joining it you don't need a thread at all. > Both the above approaches stop execution where ever these blocks are > called from. Hence I am unable to push the execution of the thread to > the background. > > Your thoughts and help ... I have no idea how your code looks and what exactly you are describing here. This is what I'd do. require 'monitor' class Example include MonitorMixin def keep_running=(x) synchronize do @keep_running = x end end def keep_running? synchronize do @keep_running end end attr_reader :thread def display self.keep_running = true @thread = Thread.new do i = 0 while keep_running? printf "%-20s %5d\n", "Background", i i += 1 sleep 1 end end end end e = Example.new e.display 10.times do |i| printf "%-20s %5d\n", "Foreground", i sleep 3 end e.keep_running = false e.thread.join puts "done." Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/