[suggestion+code] timed deq for the Queue class?

(Andrew S. Townley) #1


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
      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
      # 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

      # just read the data
        data = deq(true)
      rescue ThreadError
        # don't care
        data = nil

    # return the data value


  # This method takes a thread and unconditionally terminates
  # it, completely and utterly

  def __arnold(thread)
    thread.kill if thread && thread.alive?

  def __timeout
    puts("TIMEOUT: #{length} elements; #{num_waiting} threads waiting.")

  def __read
    puts("READ: #{length} elements; #{num_waiting} threads waiting.")

The entire program (with minimal, manual tests) is also attached.

Any/all feedback more than welcome.



fu.rb (2.47 KB)


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.