Created
March 6, 2011 18:54
-
-
Save Burgestrand/857539 to your computer and use it in GitHub Desktop.
An experiment using Fibers together with EventMachine
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding: utf-8 | |
require 'eventmachine' | |
module EM | |
module Strand | |
extend self | |
# Fires up EventMachine in a fiber, ready to take orders. | |
# | |
# @return EM::Strand | |
def start | |
@loop = ::Fiber.new { EM::run method(:event_loop) } | |
@loop.resume | |
self | |
end | |
# Executes code within the EM loop. EM::Strand.return must be called | |
# some time in the future, or this method will never terminate. | |
def resume(&block) | |
@loop.resume(lambda { instance_eval(&block) }) | |
end | |
# Wait for status to be set on the given deferrable. | |
# | |
# @param [EM::Deferrable, …] deferrables | |
# @return whatever #callback or #errback passes as params | |
def wait_for(deferrable) | |
resume do | |
deferrable.callback(method :return) | |
deferrable.errback(method :return) | |
end | |
end | |
# Return a value from within an EM::Strand.resume | |
def continue(*args) | |
event_loop(&Fiber.yield(*args)) | |
end | |
private | |
# Responsible for keeping the evented loop running. | |
def event_loop(*args) | |
if block_given? then yield | |
else | |
EM::next_tick { event_loop(&Fiber.yield) } | |
end | |
end | |
end | |
end | |
if $0 == __FILE__ | |
EM::Strand.start | |
puts "Starting…!" | |
5.times do |i| | |
done = EM::Strand.resume do | |
EM::add_timer(2) { continue "#{i}!" } | |
puts ">> waiting for #{i}…" | |
end | |
puts "Got: #{done}" | |
end | |
puts "Finished!" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How did you go with this experiment? Did it work as you hoped?