| Class | Queue |
| In: |
lib/thread.rb
|
| Parent: | 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 lib/thread.rb, line 340
340: def clear
341: @que.clear
342: end
Returns true is the queue is empty.
# File lib/thread.rb, line 333
333: def empty?
334: @que.empty?
335: end
Returns the number of threads waiting on the queue.
# File lib/thread.rb, line 359
359: def num_waiting
360: @waiting.size
361: 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 lib/thread.rb, line 309
309: def pop(non_block=false)
310: while (Thread.critical = true; @que.empty?)
311: raise ThreadError, "queue empty" if non_block
312: @waiting.push Thread.current
313: Thread.stop
314: end
315: @que.shift
316: ensure
317: Thread.critical = false
318: end
Pushes obj to the queue.
# File lib/thread.rb, line 277
277: def push(obj)
278: Thread.critical = true
279: @que.push obj
280: begin
281: t = @waiting.shift
282: t.wakeup if t
283: rescue ThreadError
284: retry
285: ensure
286: Thread.critical = false
287: end
288: begin
289: t.run if t
290: rescue ThreadError
291: end
292: end