Coroutines in Ruby
2005-02-12 9:13 AM
Ruby
Ruby
Coroutines.
class Resumable
def initialize(&proc)
@inside = nil
@outside = nil
@proc = proc
end
def callable?; @inside.nil?; end
def resumable?; [email protected]?; end
alias :done? :callable?
def call(*a)
raise "not in callable state" unless callable?
callcc do |c|
@outside = c
ret = @proc.call(self, *a)
@inside = nil
@outside.call(ret)
end
end
def resume(*a)
raise "not in a resumable state" unless resumable?
callcc do |c|
@outside = c
@inside.call(*a)
end
end
def suspend(*a)
raise "not in a suspendable state" unless @outside
callcc do |c|
@inside = c
@outside.call(*a)
end
end
end
This entry has been archived and comments are no longer accepted.