Class Coroutine
In: lib/more/facets/coroutine.rb
Parent: Object

Coroutine

Coroutines are program components like subroutines. Coroutines are more generic and flexible than subroutines, but are less widely used in practice. Coroutines were first introduced natively in Simula. Coroutines are well suited for implementing more familiar program components such as cooperative tasks, iterators, infinite lists, and pipes.

This mixin solely depends on method read(n), which must be defined in the class/module where you mix in this module.

Usage

  count = (ARGV.shift || 1000).to_i
  input = (1..count).map { (rand * 10000).round.to_f / 100}

  Producer = Coroutine.new do |me|
    loop do
      1.upto(6) do
        me[:last_input] = input.shift
        me.resume(Printer)
      end
      input.shift # discard every seventh input number
    end
  end
  Printer = Coroutine.new do |me|
    loop do
      1.upto(8) do
        me.resume(Producer)
        if Producer[:last_input]
          print Producer[:last_input], "\t"
          Producer[:last_input] = nil
        end
        me.resume(Controller)
      end
      puts
    end
  end

  Controller = Coroutine.new do |me|
    until input.empty? do
      me.resume(Printer)
    end
  end

  Controller.run

Methods

[]   []=   continue   new   resume   run   stop  

Attributes

stopped  [R] 

Public Class methods

[Source]

     # File lib/more/facets/coroutine.rb, line 115
115:   def initialize(data = {})
116:     @stopped = nil
117:     @data = data
118:     callcc do |@continue|
119:       return
120:     end
121:     yield self
122:     stop
123:   end

Public Instance methods

[Source]

     # File lib/more/facets/coroutine.rb, line 148
148:   def [](name)
149:     @data[name]
150:   end

[Source]

     # File lib/more/facets/coroutine.rb, line 152
152:   def []=(name, value)
153:     @data[name] = value
154:   end

[Source]

     # File lib/more/facets/coroutine.rb, line 137
137:   def resume(other)
138:     callcc do |@continue|
139:       other.continue(self)
140:     end
141:   end

[Source]

     # File lib/more/facets/coroutine.rb, line 127
127:   def run
128:     callcc do |@stopped|
129:       continue
130:     end
131:   end

[Source]

     # File lib/more/facets/coroutine.rb, line 133
133:   def stop
134:     @stopped.call
135:   end

Protected Instance methods

[Source]

     # File lib/more/facets/coroutine.rb, line 143
143:   def continue(from = nil)
144:     @stopped = from.stopped if not @stopped and from
145:     @continue.call
146:   end

[Validate]