The Thread::Queue class implements multi-producer, multi-consumer queues. It is especially useful in threaded programming when information must be exchanged safely between multiple threads. The Thread::Queue class implements all the required locking semantics.

The class implements FIFO type of queue. In a FIFO queue, the first tasks added are the first retrieved.


queue =

producer = do
  5.times do |i|
     sleep rand(i) # simulate expense
     queue << i
     puts "#{i} produced"

consumer = do
  5.times do |i|
     value = queue.pop
     sleep rand(i/2) # simulate expense
     puts "consumed #{value}"

Class Methods

Creates a new queue instance, optionally using the contents of an enumerable for its initial state.


q =
#=> #<Thread::Queue:0x00007ff7501110d0>
#=> true

q =[1, 2, 3])
#=> #<Thread::Queue:0x00007ff7500ec500>
#=> false
#=> 1
Instance Methods
An alias for push

Removes all objects from the queue.

Closes the queue. A closed queue cannot be re-opened.

After the call to close completes, the following are true:

  • closed? will return true

  • close will be ignored.

  • calling enq/push/<< will raise a ClosedQueueError.

  • when empty? is false, calling deq/pop/shift will return an object from the queue as usual.

  • when empty? is true, deq(false) will not suspend the thread and will return nil. deq(true) will raise a ThreadError.

ClosedQueueError is inherited from StopIteration, so that you can break loop block.


q ={
  while e = q.deq # wait for nil to break loop
    # ...

Returns true if the queue is closed.

Returns true if the queue is empty.

An alias for push

Returns the length of the queue.

Returns the number of threads waiting on the queue.

Retrieves data from the queue.

If the queue is empty, the calling thread is suspended until data is pushed onto the queue. If non_block is true, the thread isn’t suspended, and ThreadError is raised.

If timeout seconds have passed and no data is available nil is returned. If timeout is 0 it returns immediately.

Pushes the given object to the queue.

An alias for length