123456789_123456789_123456789_123456789_123456789_

Class: Queue

Relationships & Source Files
Inherits: Object
Defined in: thread_sync.c,
thread_sync.c

Overview

The 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 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.

Example:

require 'thread'
queue = Queue.new

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

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

Class Method Summary

  • .new constructor

    Creates a new queue instance.

Instance Attribute Summary

Instance Method Summary

Constructor Details

.new

Creates a new queue instance.

Instance Attribute Details

#closed?Boolean (readonly)

Returns true if the queue is closed.

#empty?Boolean (readonly)

Returns true if the queue is empty.

Instance Method Details

#push(object) #enq(object) #<<(object)
Also known as: #push, #enq

Pushes the given object to the queue.

#clear

Removes all objects from the queue.

#close

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 return nil.

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

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

Example:

    q = Queue.new
    Thread.new{
      while e = q.deq # wait for nil to break loop
        # ...
      end
    }
    q.close

#pop(non_block = false) #deq(non_block = false) #shift(non_block = false)
Also known as: #pop, #shift

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.

#push(object) #enq(object) #<<(object)

Alias for #<<.

#length #size
Also known as: #size

Returns the length of the queue.

#num_waiting

Returns the number of threads waiting on the queue.

#pop(non_block = false) #deq(non_block = false) #shift(non_block = false)

Alias for #deq.

#push(object) #enq(object) #<<(object)

Alias for #<<.

#pop(non_block = false) #deq(non_block = false) #shift(non_block = false)

Alias for #deq.

#length #size

Alias for #length.