On Wed, Jun 8, 2011 at 11:52 AM, Iain Barnett <iainspeed / gmail.com> wrote:
> Hi all,
>
> Just wondering if anyone can recommend some articles/tutorials on fibers and async stuff? I've had a look around of course, but it always
> seems to be the same example of an HTTP server, or some explanation of theory. Call me an ignoramus (go on, it's relaxing) but I don't
> really care about the theory, some good examples moving from the simple to the not so simple in nice gradations would be muy bueno!

There isn't really a lot involved with fibers.  Replace that HTTP
request with anything else, and you get the same basic example.

There are some nuances between the use of #transfer and #resume, but
the method count on Fiber is very small, so there isn't a lot to
learn. Just take one of the examples from one of the existing articles
and experiment a little bit, and you will have the topic well
explored.

There's nothing extra that needs to happen to link it with
EventMachine, either, since the Fiber API is already so shallow.

# 1) Create Fiber.
Fiber.new do

    # 2) Blah blah blah code that does whatever your code does.

    # 3) Grab the current fiber.
    f = Fiber.current

    # 4) Create some EventMachine protocol object that will do
something for you.
    something_doer = EventMachine::Doer.new(stuff).doit

    # 5) Setup the callback to wake the fiber up when it's done.
    something_doer.callback { f.resume (something_doer) }

    # 6) Suspend this fiber so that something else can run.
    Fiber.yield

    # 7) More blah blah blah that you want to do after your
EventMachine::Doer finishes it's stuff.

end

If you wrap #3-#6 in a method, then you can call into it via a nice
clean API, treating it just like it were a simple blocking call, and
whatever is doing it need not even know that it is an asynchronous,
nonblocking call. As far as your code, and your thought process while
writing the code is concerned, it will call into the method, and get a
return value from the method. This is the strength of fibers when used
with something like EventMachine, in my opinion. You can make your API
simpler to understand by using fibers to hide the asynchronous nature
of what is happening behind it.

Just work with that basic template, which is what you will find in
most any example, and you should have it figured out pretty quickly.

I have a very simple presentation on this that I did for the
EMRubyConf at RailsConf. I should find out if there is an official
place for these things, but if you want to see it, you can get it
here: http://kirk.swiftcore.org/emrubyconf_fibers_presentation.pdf


Kirk Haines
Developer
Engine Yard