From: Robert Klemme Date: 2008-03-25T20:57:48+09:00 Subject: Re: thread.rb 2008/3/25, Adam Bender : > I want to modify the Queue class in thread.rb, so I first searched for Why? > P.S. On a related note, I want to add a method to the Queue class that > is similar to pop, but will take a timeout value and return nil if it > no item is push'ed before timeout seconds have elapsed. Can anyone > suggest something better than the following: > > class Queue > def pop_with_timeout(timeout) > elapsed = 0.0 > while (Thread.critical = true; @que.empty?) > @waiting.push Thread.current > Thread.critical = false > elapsed += sleep(timeout - elapsed) > puts elapsed > return nil if elapsed >= timeout > end > @que.shift > ensure > Thread.critical = false > end > end > > That was the first thing I came up with, and I'm (again) surprised > that it works - why does sleep ever return less than 1? What > interrupts it? I opt against using Thread.critical because this is a global exclusive lock on all threads and it is unlikely to continue to exist in the light of JRuby and others. I'd rather use Mutex#try_lock or Monitor's #wait with timeout parameter. Kind regards robert -- use.inject do |as, often| as.you_can - without end