igrigorik/em-synchrony — Issue #80: An EM.schedule-esque for Fibers
Author: slyphon
Created: 2011-11-02 05:08:01+00:00
State: open

One thing I've found handy while integrating/migrating my code to use EM::Synchrony is the following:

```ruby

module FiberHelper
mattr_accessor :root_fiber, :instance_writer => false, :instance_reader => false

def self.root_fiber?
root_fiber == Fiber.current
end

def ensure_fiber(&blk)
if FiberHelper.root_fiber?
Fiber.new { blk.call }.resume
else
blk.call
end
end
end

FiberHelper.root_fiber ||= Fiber.current

```

If we're already running in some fibrous context, one doesn't need to do the wrapping. Much in the same way that `EM.schedule` is handy when you're trying to ensure that some thread doesn't trample your async code: if you're already in the reactor, great! otherwise, make things safe.

This way, as I'm going through and converting methods one at a time, I can just wrap the body in `ensure_fiber` and I don't have to worry about the calling context.

Thought it might make a decent convenience feature (with a slightly better name, perhaps).