Class: LazyList::ReadQueue

Inherits:
Object show all
Defined in:
lib/lazylist/thread_queue.rb,
lib/lazylist/enumerator_queue.rb

Overview

ReadQueue is the implementation of an read-only queue that only supports #shift and #empty? methods. It’s used as a wrapper to encapsulate enumerables in lazy lists.

Instance Method Summary collapse

Constructor Details

#initialize(enumerable) ⇒ ReadQueue

Creates an ReadQueue object from an enumerable.



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/lazylist/thread_queue.rb', line 7

def initialize(enumerable)
  @data = []
  @producer = Thread.new do
    Thread.stop
    begin
      enumerable.each do |value|
        old, Thread.critical = Thread.critical, true
        begin
          @data << value
          @consumer.wakeup
          Thread.stop
        ensure
          Thread.critical = old
        end
      end
    rescue => e
      @consumer.raise e
    ensure
      @consumer.wakeup
    end
  end
  Thread.pass until @producer.stop?
end

Instance Method Details

#empty?Boolean

Returns true if the queue is empty.

Returns:

  • (Boolean)


44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/lazylist/thread_queue.rb', line 44

def empty?
  if @data.empty?
    old, Thread.critical = Thread.critical, true
    begin
      @consumer = Thread.current
      @producer.wakeup
      Thread.stop
    rescue ThreadError
      ;
    ensure
      @consumer = nil
      Thread.critical = old
    end
  end
  @data.empty?
end

#shiftObject Also known as: pop

Extracts the top element from the queue or nil if the queue is empty.



33
34
35
36
37
38
39
# File 'lib/lazylist/thread_queue.rb', line 33

def shift
  if empty?
    nil
  else
    @data.shift
  end
end