Class: OsCtl::Lib::Queue

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

Overview

Replacement for stock Queue

Instance Method Summary collapse

Constructor Details

#initializeQueue

Returns a new instance of Queue



6
7
8
9
10
# File 'lib/libosctl/queue.rb', line 6

def initialize
  @mutex = ::Mutex.new
  @cond = ConditionVariable.new
  @queue = []
end

Instance Method Details

#any?Boolean

Returns:

  • (Boolean)


62
63
64
# File 'lib/libosctl/queue.rb', line 62

def any?
  !empty?
end

#clearObject

Clear the queue



52
53
54
# File 'lib/libosctl/queue.rb', line 52

def clear
  sync { @queue.clear }
end

#empty?Boolean

Returns:

  • (Boolean)


57
58
59
# File 'lib/libosctl/queue.rb', line 57

def empty?
  sync { @queue.empty? }
end

#push(v) ⇒ Object Also known as: <<

Add value into queue



13
14
15
16
17
18
# File 'lib/libosctl/queue.rb', line 13

def push(v)
  sync do
    @queue << v
    @cond.signal
  end
end

#shift(block: true, timeout: nil) ⇒ Object Also known as: pop

Remove the first element from the queue and return it

If `block` is `true`, this method will block until there is something to return. If `block` is `false` and the queue is empty, `nil` is returned. If `timeout` is set and passes, `nil` is returned.

Parameters:

  • block (Boolean)

    block if the queue is empty

  • timeout (Integer, nil)

    how many seconds to wait



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

def shift(block: true, timeout: nil)
  sync do
    if @queue.any?
      @queue.shift

    elsif block # Wait for something to be pushed
      loop do
        @cond.wait(@mutex, timeout)
        break if @queue.any? || timeout
      end

      @queue.shift

    else
      nil
    end
  end
end

#syncObject (protected)



73
74
75
# File 'lib/libosctl/queue.rb', line 73

def sync
  @mutex.synchronize { yield }
end

#to_aArray

Return the queued values as an array

Returns:

  • (Array)


68
69
70
# File 'lib/libosctl/queue.rb', line 68

def to_a
  sync { @queue.clone }
end