From: ptkwt@...1.aracnet.com (Phil Tomson) Date: 2001-12-07T06:54:03+09:00 Subject: [ruby-talk:27754] timeout within Threads (do I need a mutex?) I have a class which has a 'run' method which sends objects off to a remote dRuby object to be run on differnt client machines. I'll reduce the code as much as possible and hopefully still retain the essence of the problem. There is a Distributor class that distributes objects to different clients based on availability (established by checking a @status variable in the ClientProxy every second). There is a ClientProxy class that establishes the dRuby connection to the remote dRuby Client. The relevant method(s) of ClientProxy: class ClientProxy def initialize(name) @name = name @drbObj = DRbObject.new(nil, "druby://#{name}:9000") @status = "AVAILABLE" end def run(whatToRun,*args) @thread = Thread.start do @status = "BUSY" #<=works here begin timeout(@serverTimeLimit) do #@status = "BUSY" #<=doesn't work here @drbObj.run(whatToRun,*args) end #timeout rescue TimeoutError #server-side timeout-assume client is dead @status = "TIMED_OUT" @drbObj = nil #break the connection else #all was well @status = "FINISHED" #unless @thread.alive?#completed task #before timeout end end #Thread end #run #... end #ClientProxy The Distributor class basically has a list of ClientProxy's and when it's send_task method is called it queries the status of all of the ClientProxy's to find a client in the "AVAILABLE" state and then sends the task to that client - if none of the ClientProxy's in the list are available it sleeps for 1 second and then checks again until it finds one AVAILABLE. Notice the two assignments of "BUSY" to @status above in the ClientProxy code. The second one is commented out and followed by a comment that says:' #<= doesn't work here'. Originally, I was making @status BUSY within the timeout block, but what tended to happen was that the Distributor would poll and find that @status was AVAILABLE even right after a long job was sent out to the same ClientProxy - externally, @status remained AVAILABLE even though it should have been changed to BUSY. After I put the '@status = "BUSY"' right after the thread creation it worked correctly - is this because timeout launches it's own thread? To be absolutely safe with the assignments to @status, do I need to use a Mutex (even with the current configuration where the assignment to @status now is done outside of the timeout block)? Perhaps I need to ensure that access to @status from the main thread and the created thread is synchronized - opinions? Phil