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

Methods

<<   clear   deq   empty?   enq   length   new   num_waiting   pop   push   shift   size  

Public Class methods

Creates a new queue.

[Source]

     # File lib/thread.rb, line 271
271:   def initialize
272:     @que = []
273:     @waiting = []
274:     @que.taint          # enable tainted comunication
275:     @waiting.taint
276:     self.taint
277:   end

Public Instance methods

<<(obj)

Alias for push

Removes all objects from the queue.

[Source]

     # File lib/thread.rb, line 345
345:   def clear
346:     @que.clear
347:   end
deq(non_block=false)

Alias for pop

Returns true is the queue is empty.

[Source]

     # File lib/thread.rb, line 338
338:   def empty?
339:     @que.empty?
340:   end
enq(obj)

Alias for push

Returns the length of the queue.

[Source]

     # File lib/thread.rb, line 352
352:   def length
353:     @que.length
354:   end

Returns the number of threads waiting on the queue.

[Source]

     # File lib/thread.rb, line 364
364:   def num_waiting
365:     @waiting.size
366:   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.

[Source]

     # File lib/thread.rb, line 314
314:   def pop(non_block=false)
315:     while (Thread.critical = true; @que.empty?)
316:       raise ThreadError, "queue empty" if non_block
317:       @waiting.push Thread.current
318:       Thread.stop
319:     end
320:     @que.shift
321:   ensure
322:     Thread.critical = false
323:   end

Pushes obj to the queue.

[Source]

     # File lib/thread.rb, line 282
282:   def push(obj)
283:     Thread.critical = true
284:     @que.push obj
285:     begin
286:       t = @waiting.shift
287:       t.wakeup if t
288:     rescue ThreadError
289:       retry
290:     ensure
291:       Thread.critical = false
292:     end
293:     begin
294:       t.run if t
295:     rescue ThreadError
296:     end
297:   end
shift(non_block=false)

Alias for pop

size()

Alias for length

[Validate]