This class provides a way to synchronize communication between threads.

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

consumer.join
Methods
#
C
D
E
L
N
P
S
Class Public methods
new()

Creates a new queue.

# File ../ruby/lib/thread.rb, line 144
def initialize
  @que = []
  @waiting = []
  @que.taint          # enable tainted communication
  @waiting.taint
  self.taint
  @mutex = Mutex.new
end
Instance Public methods
<<(obj)

Alias of push

Alias for: push
clear()

Removes all objects from the queue.

# File ../ruby/lib/thread.rb, line 217
def clear
  @que.clear
end
deq(non_block=false)

Alias of pop

Alias for: pop
empty?()

Returns true if the queue is empty.

# File ../ruby/lib/thread.rb, line 210
def empty?
  @que.empty?
end
enq(obj)

Alias of push

Alias for: push
length()

Returns the length of the queue.

Also aliased as: size
# File ../ruby/lib/thread.rb, line 224
def length
  @que.length
end
num_waiting()

Returns the number of threads waiting on the queue.

# File ../ruby/lib/thread.rb, line 236
def num_waiting
  @waiting.size
end
pop(non_block=false)

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 an exception is raised.

Also aliased as: shift, deq
# File ../ruby/lib/thread.rb, line 183
def pop(non_block=false)
  @mutex.synchronize{
    while true
      if @que.empty?
        raise ThreadError, "queue empty" if non_block
        @waiting.push Thread.current
        @mutex.sleep
      else
        return @que.shift
      end
    end
  }
end
push(obj)

Pushes obj to the queue.

Also aliased as: <<, enq
# File ../ruby/lib/thread.rb, line 156
def push(obj)
  @mutex.synchronize{
    @que.push obj
    begin
      t = @waiting.shift
      t.wakeup if t
    rescue ThreadError
      retry
    end
  }
end
shift(non_block=false)

Alias of pop

Alias for: pop
size()

Alias of length.

Alias for: length