Class: LightIO::Library::Queue

Inherits:
Object
  • Object
show all
Extended by:
Base::MockMethods
Defined in:
lib/lightio/library/queue.rb

Direct Known Subclasses

SizedQueue

Instance Method Summary collapse

Constructor Details

#initializeQueue

Returns a new instance of Queue.



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

def initialize
  @queue = []
  @waiters = []
  @close = false
end

Instance Method Details

#clearObject

Removes all objects from the queue.



84
85
86
87
# File 'lib/lightio/library/queue.rb', line 84

def clear()
  @queue.clear
  self
end

#closeObject



12
13
14
15
16
17
# File 'lib/lightio/library/queue.rb', line 12

def close()
  #This is a stub, used for indexing
  @close = true
  @waiters.each {|w| w.transfer nil}
  self
end

#closed?Boolean

closed?

Returns true if the queue is closed.

Returns:

  • (Boolean)


22
23
24
# File 'lib/lightio/library/queue.rb', line 22

def closed?()
  @close
end

#empty?Boolean

empty?

Returns true if the queue is empty.

Returns:

  • (Boolean)


79
80
81
# File 'lib/lightio/library/queue.rb', line 79

def empty?()
  @queue.empty?
end

#lengthObject Also known as: size

length size

Returns the length of the queue.



93
94
95
# File 'lib/lightio/library/queue.rb', line 93

def length()
  @queue.size
end

#num_waitingObject

Returns the number of threads waiting on the queue.



99
100
101
# File 'lib/lightio/library/queue.rb', line 99

def num_waiting()
  @waiters.size
end

#pop(non_block = false) ⇒ Object Also known as: deq, shift

pop(non_block=false) deq(non_block=false) shift(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.



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/lightio/library/queue.rb', line 57

def pop(non_block=false)
  if @close
    return empty? ? nil : @queue.pop
  end
  if empty?
    if non_block
      raise ThreadError, 'queue empty'
    else
      future = LightIO::Future.new
      @waiters << future
      future.value
    end
  else
    @queue.pop
  end
end

#push(object) ⇒ Object Also known as: enq, <<

push(object) enq(object) <<(object)

Pushes the given object to the queue.

Raises:

  • (ClosedQueueError)


31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/lightio/library/queue.rb', line 31

def push(object)
  raise ClosedQueueError, "queue closed" if @close
  if (waiter = @waiters.shift)
    future = LightIO::Future.new
    LightIO::IOloop.current.add_callback {
      waiter.transfer(object)
      future.transfer
    }
    future.value
  else
    @queue << object
  end
  self
end