Class: Coroutine
Overview
:title: 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.
Usage
require 'mega/coroutine'
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
puts
Author(s)
-
Florian Frank
Instance Method Summary collapse
- #[](name) ⇒ Object
- #[]=(name, value) ⇒ Object
-
#initialize(data = {}) {|_self| ... } ⇒ Coroutine
constructor
A new instance of Coroutine.
- #resume(other) ⇒ Object
- #run ⇒ Object
- #stop ⇒ Object
Constructor Details
#initialize(data = {}) {|_self| ... } ⇒ Coroutine
Returns a new instance of Coroutine.
74 75 76 77 78 79 80 81 |
# File 'lib/mega/coroutine.rb', line 74 def initialize(data = {}) @data = data callcc do |@continue| return end yield self stop end |
Instance Method Details
#[](name) ⇒ Object
106 107 108 |
# File 'lib/mega/coroutine.rb', line 106 def [](name) @data[name] end |
#[]=(name, value) ⇒ Object
110 111 112 |
# File 'lib/mega/coroutine.rb', line 110 def []=(name, value) @data[name] = value end |
#resume(other) ⇒ Object
95 96 97 98 99 |
# File 'lib/mega/coroutine.rb', line 95 def resume(other) callcc do |@continue| other.continue(self) end end |
#run ⇒ Object
85 86 87 88 89 |
# File 'lib/mega/coroutine.rb', line 85 def run callcc do |@stopped| continue end end |
#stop ⇒ Object
91 92 93 |
# File 'lib/mega/coroutine.rb', line 91 def stop @stopped.call end |