Class: Queue

Class | Queue
In: | 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

new()

Creates a new queue.

[Source]

    # File thread.rb, line 271
      def initialize
        @que = []
        @waiting = []
        @que.taint          # enable tainted comunication
        @waiting.taint
        self.taint
      end

### Public Instance methods

<<(obj)

Alias for push

clear()

Removes all objects from the queue.

[Source]

    # File thread.rb, line 345
      def clear
        @que.clear
      end

deq(non_block=false)

Alias for pop

empty?()

Returns `true` is the queue is empty.

[Source]

    # File thread.rb, line 338
      def empty?
        @que.empty?
      end

enq(obj)

Alias for push

length()

Returns the length of the queue.

[Source]

    # File thread.rb, line 352
      def length
        @que.length
      end

num_waiting()

Returns the number of threads waiting on the queue.

[Source]

    # File thread.rb, line 364
      def num_waiting
        @waiting.size
      end

pop(non_block=false)

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 thread.rb, line 314
      def pop(non_block=false)
        while (Thread.critical = true; @que.empty?)
          raise ThreadError, "queue empty" if non_block
          @waiting.push Thread.current
          Thread.stop
        end
        @que.shift
      ensure
        Thread.critical = false
      end

push(obj)

Pushes `obj` to the queue.

[Source]

    # File thread.rb, line 282
      def push(obj)
        Thread.critical = true
        @que.push obj
        begin
          t = @waiting.shift
          t.wakeup if t
        rescue ThreadError
          retry
        ensure
          Thread.critical = false
        end
        begin
          t.run if t
        rescue ThreadError
        end
      end

shift(non_block=false)

Alias for pop

size()

Alias for length

[Validate]