Class: Goru::Queue

Inherits:
Object
  • Object
show all
Defined in:
lib/goru/queue.rb

Overview

Instance Method Summary collapse

Constructor Details

#initializeQueue

Returns a new instance of Queue.



7
8
9
10
11
12
# File 'lib/goru/queue.rb', line 7

def initialize
  @mutex = Mutex.new
  @queue = []
  @received = ConditionVariable.new
  @closed = false
end

Instance Method Details

#<<(x) ⇒ Object

public


16
17
18
19
20
21
# File 'lib/goru/queue.rb', line 16

def <<(x)
  @mutex.synchronize do
    @queue << x
    @received.signal
  end
end

#closeObject

public


54
55
56
57
58
59
# File 'lib/goru/queue.rb', line 54

def close
  @mutex.synchronize do
    @closed = true
    @received.broadcast
  end
end

#pop(non_block = false) ⇒ Object

public


25
26
27
# File 'lib/goru/queue.rb', line 25

def pop(non_block = false)
  pop_with_timeout(non_block ? 0 : nil)
end

#pop_with_timeout(timeout = nil) ⇒ Object

public


31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/goru/queue.rb', line 31

def pop_with_timeout(timeout = nil)
  @mutex.synchronize do
    if timeout.nil?
      # wait indefinitely until there is an element in the queue
      while @queue.empty? && !@closed
        @received.wait(@mutex)
      end
    elsif @queue.empty? && !@closed && timeout != 0
      # wait for element or timeout
      timeout_time = timeout + Time.now.to_f
      while @queue.empty? && (remaining_time = timeout_time - Time.now.to_f) > 0
        @received.wait(@mutex, remaining_time)
      end
    end
    return if @closed
    # if we're still empty after the timeout, raise exception
    raise ThreadError, "queue empty" if @queue.empty?
    @queue.shift
  end
end