Class | Coroutine |
In: |
lib/more/facets/coroutine.rb
|
Parent: | Object |
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.
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
stopped | [R] |
# 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
# File lib/more/facets/coroutine.rb, line 152 152: def []=(name, value) 153: @data[name] = value 154: end
# File lib/more/facets/coroutine.rb, line 137 137: def resume(other) 138: callcc do |@continue| 139: other.continue(self) 140: end 141: end
# File lib/more/facets/coroutine.rb, line 127 127: def run 128: callcc do |@stopped| 129: continue 130: end 131: end