Skip to content

Instantly share code, notes, and snippets.

@Burgestrand
Created March 6, 2011 18:54
Show Gist options
  • Save Burgestrand/857539 to your computer and use it in GitHub Desktop.
Save Burgestrand/857539 to your computer and use it in GitHub Desktop.
An experiment using Fibers together with EventMachine
# 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
@saward
Copy link

saward commented Dec 26, 2012

How did you go with this experiment? Did it work as you hoped?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment