Class: Green::Group

Inherits:
Object
  • Object
show all
Defined in:
lib/green/group.rb

Direct Known Subclasses

Pool

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Group

Returns a new instance of Group.



6
7
8
9
10
# File 'lib/green/group.rb', line 6

def initialize(options = {})
  @options = options
  @options[:klass] ||= ::Green
  @greens = []
end

Instance Attribute Details

#greensObject (readonly)

Returns the value of attribute greens.



5
6
7
# File 'lib/green/group.rb', line 5

def greens
  @greens
end

#optionsObject (readonly)

Returns the value of attribute options.



5
6
7
# File 'lib/green/group.rb', line 5

def options
  @options
end

Instance Method Details

#add(green) ⇒ Object



25
26
27
# File 'lib/green/group.rb', line 25

def add(green)
  greens << green
end

#apply(&blk) ⇒ Object



21
22
23
# File 'lib/green/group.rb', line 21

def apply(&blk)
  spawn(&blk).join
end

#discard(green) ⇒ Object



29
30
31
# File 'lib/green/group.rb', line 29

def discard(green)
  greens.delete green
end

#enumerator(iterable, &blk) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/green/group.rb', line 47

def enumerator(iterable, &blk)
  iter = iterable.each
  Enumerator.new do |y|
    e = Event.new
    begin
      waiting = 0
      while true
        i = iter.next
        waiting += 1
        spawn(i) do |item|
          y << blk.call(item)
          waiting -= 1
          e.set if waiting == 0
        end
      end
    rescue StopIteration
      e.wait
    end
  end
end

#joinObject



33
34
35
36
37
# File 'lib/green/group.rb', line 33

def join
  while (g = greens.first)
    g.join
  end
end

#killObject



39
40
41
# File 'lib/green/group.rb', line 39

def kill
  greens.each(&:kill)
end

#sizeObject



43
44
45
# File 'lib/green/group.rb', line 43

def size
  greens.size
end

#spawn(*args, &blk) ⇒ Object



12
13
14
15
16
17
18
19
# File 'lib/green/group.rb', line 12

def spawn(*args, &blk)
  g = @options[:klass].spawn do
    blk.call(*args)
  end
  add g
  g.callback { discard g }
  g
end