Object
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
Removes all objects from the queue.
# File thread.rb, line 213
def clear
@que.clear
end
Returns true if the queue is empty.
# File thread.rb, line 206
def empty?
@que.empty?
end
Returns the length of the queue.
# File thread.rb, line 220
def length
@que.length
end
Returns the number of threads waiting on the queue.
# File thread.rb, line 232
def num_waiting
@waiting.size
end
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.
# File thread.rb, line 179
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