From: Adam Bender Date: 2008-03-26T02:04:43+09:00 Subject: Re: thread.rb On Tue, Mar 25, 2008 at 7:57 AM, Robert Klemme wrote: > 2008/3/25, Adam Bender : > > > I want to modify the Queue class in thread.rb, so I first searched for > > Why? > What what? I want to modify the class as described below; I searched for the file so I could see how pop was implemented and the class variables it used. > > 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. The Queue class uses Thread.critical. Though I guess writing a queue using a Monitor would be easy enough to do. Adam