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 266
266:   def initialize
267:     @que = []
268:     @waiting = []
269:     @que.taint          # enable tainted comunication
270:     @waiting.taint
271:     self.taint
272:   end

Public Instance methods

<<(obj)

Alias for push

Removes all objects from the queue.

[Source]

     # File lib/thread.rb, line 340
340:   def clear
341:     @que.clear
342:   end
deq(non_block=false)

Alias for pop

Returns true is the queue is empty.

[Source]

     # File lib/thread.rb, line 333
333:   def empty?
334:     @que.empty?
335:   end
enq(obj)

Alias for push

Returns the length of the queue.

[Source]

     # File lib/thread.rb, line 347
347:   def length
348:     @que.length
349:   end

Returns the number of threads waiting on the queue.

[Source]

     # 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.

[Source]

     # 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.

[Source]

     # 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
shift(non_block=false)

Alias for pop

size()

Alias for length

[Validate]