Class: Coroutine

Inherits:
Object show all
Defined in:
lib/mega/coroutine.rb

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

Constructor Details

#initialize(data = {}) {|_self| ... } ⇒ Coroutine

Returns a new instance of Coroutine.

Yields:

  • (_self)

Yield Parameters:

  • _self (Coroutine)

    the object that the method was called on



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

#runObject



85
86
87
88
89
# File 'lib/mega/coroutine.rb', line 85

def run
  callcc do |@stopped|
    continue
  end
end

#stopObject



91
92
93
# File 'lib/mega/coroutine.rb', line 91

def stop
  @stopped.call
end