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.



4
5
6
7
8
# File 'lib/libosctl/queue.rb', line 4

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

Instance Method Details

#any?Boolean

Returns:

  • (Boolean)


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

def any?
  !empty?
end

#clearObject

Clear the queue



64
65
66
# File 'lib/libosctl/queue.rb', line 64

def clear
  sync { @queue.clear }
end

#empty?Boolean

Returns:

  • (Boolean)


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

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

#insert(v) ⇒ Object

Insert value to the beginning of the queue

Parameters:

  • v (any)


22
23
24
25
26
27
# File 'lib/libosctl/queue.rb', line 22

def insert(v)
  sync do
    @queue.insert(0, v)
    @cond.signal
  end
end

#lengthObject



78
79
80
# File 'lib/libosctl/queue.rb', line 78

def length
  sync { @queue.length }
end

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

Add value into queue



11
12
13
14
15
16
# File 'lib/libosctl/queue.rb', line 11

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) (defaults to: true)

    block if the queue is empty

  • timeout (Integer, nil) (defaults to: nil)

    how many seconds to wait



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/libosctl/queue.rb', line 37

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

    if timeout
      deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + timeout

      loop do
        remaining = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC)
        return if remaining <= 0

        @cond.wait(@mutex, remaining)
        return @queue.shift if @queue.any?
      end
    end

    loop do
      @cond.wait(@mutex)
      return @queue.shift if @queue.any?
    end
  end
end

#syncObject (protected)



90
91
92
# File 'lib/libosctl/queue.rb', line 90

def sync(&)
  @mutex.synchronize(&)
end

#to_aArray

Return the queued values as an array

Returns:

  • (Array)


84
85
86
# File 'lib/libosctl/queue.rb', line 84

def to_a
  sync { @queue.clone }
end