From: "Andrew S. Townley" Date: 2005-09-01T05:10:02+09:00 Subject: [suggestion+code] timed deq for the Queue class? --=-6YcQHYoBJJLKKdsYFNhU Content-Type: text/plain Content-Transfer-Encoding: 7bit Hi, Based on my earlier emails and further thinking, I've implemented the following methods which seem to work and which other people might find useful. No guarantees that they're 100% correct, but it seems to do what I want. Would it be possible to add something like this to the standard Queue? $ cat fu.rb require 'thread' require 'timeout' class TimedReadQueue < Queue # Waits for the specified timeout (seconds) and returns, # waking up the accessing thread. This method avoids a # problem with using Timeout and Queue together to achieve # the same result. def tdeq(timeout) data = nil if(empty?) mt = Thread.current # This thread will wait for the timeout. If it is still # alive, it will remove the read thread (rt) from the # waiting list, kill it and restart the main thread. rt = nil tt = Thread.new do Thread.stop; sleep(timeout); @waiting.delete(rt); mt.wakeup __timeout end # This thread will actually try and read the data. If # it gets data, it will kill the timer and wake up the # main thread. rt = Thread.new do Thread.stop; data = deq; __arnold(tt); mt.wakeup __read end begin tt.run rt.run Thread.stop ensure mt.wakeup __arnold(tt) __arnold(rt) end else # just read the data begin data = deq(true) rescue ThreadError # don't care data = nil end end # return the data value data end private # This method takes a thread and unconditionally terminates # it, completely and utterly def __arnold(thread) thread.kill if thread && thread.alive? end def __timeout puts("TIMEOUT: #{length} elements; #{num_waiting} threads waiting.") end def __read puts("READ: #{length} elements; #{num_waiting} threads waiting.") end end The entire program (with minimal, manual tests) is also attached. Any/all feedback more than welcome. Cheers, ast *************************************************************************************************** The information in this email is confidential and may be legally privileged. Access to this email by anyone other than the intended addressee is unauthorized. If you are not the intended recipient of this message, any review, disclosure, copying, distribution, retention, or any action taken or omitted to be taken in reliance on it is prohibited and may be unlawful. If you are not the intended recipient, please reply to or forward a copy of this message to the sender and delete the message, any attachments, and any copies thereof from your system. *************************************************************************************************** --=-6YcQHYoBJJLKKdsYFNhU Content-Disposition: attachment; filename=fu.rb Content-Type: text/plain; name=fu.rb; charset=ANSI_X3.4-1968 Content-Transfer-Encoding: base64 cmVxdWlyZSAnd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