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 230
def clear
@que.clear
self
end
Returns true if the queue is empty.
# File thread.rb, line 223
def empty?
@que.empty?
end
Returns the length of the queue.
# File thread.rb, line 238
def length
@que.length
end
Returns the number of threads waiting on the queue.
# File thread.rb, line 250
def num_waiting
@num_waiting
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 187
def pop(non_block=false)
Thread.handle_interrupt(StandardError => :on_blocking) do
@mutex.synchronize do
while true
if @que.empty?
if non_block
raise ThreadError, "queue empty"
else
begin
@num_waiting += 1
@cond.wait @mutex
ensure
@num_waiting -= 1
end
end
else
return @que.shift
end
end
end
end
end
Commenting is here to help enhance the documentation. For example, code samples, or clarification of the documentation.
If you have questions about Ruby or the documentation, please post to one of the Ruby mailing lists. You will get better, faster, help that way.
If you wish to post a correction of the docs, please do so, but also file bug report so that it can be corrected for the next release. Thank you.
If you want to help improve the Ruby documentation, please see Improve the docs, or visit Documenting-ruby.org.