An Introduction To Fibers

You know Thread, but have you heard of his red haired step child? Fiber? Fibers are a new and a note worthy addition to Ruby that appeared with 1.9. They are essentially code blocks that can be paused and resumed. They have to be forced to do so, unlike threads which are well mannered and just step aside when someone is in a hurry. Fibers are not a totally new ideas, they have been known for ages as Coroutines. But how does those fibers work? Let’s start by the canonical example:

The very first time we called resume, the fiber sprang to life and the loop started, then when it hit Fiber.yield it returned to the caller with the value to the right side of the Fiber.yield (i in this case which is equal to zero in the first iteration). When resume is called again, the fiber continues from where it stopped so the loop continues, i picks the value 1 and then yields it back. This continues till the fiber block is exhausted, at this point, calling resume on the fiber will raise an error.

Fibers can do two way communication

When you resume a fiber, you get the right side of the Fiber.yield statement as a return value. That way the fiber sends us messages or data. The good thing is that we too can send data to the fiber in return. Example:

That is, the value you sent in the first resume was passed to the fiber as the block parameter. Now what about changing the earlier example so we can send data many times to the fiber?

What is going on? it keeps spitting crazy 8’s at us even if we change the value we send in resume. It turns out that the block parameter will get bound in the very first call and live with you afterwards. Still, the data you pass in the resume is what the term Fiber.yield x evaluates to. So given this tiny update:

Nice, whenever we call resume with a value, the Fiber.yield x statement evaluates into it. This way we can send messages to the fiber as much as we can get messages from it.

In another article we will explain how fibers can be pooled. We will go through the fiber pool implementation that lives in the NeverBlock library.

Comments

1.

When will the sequel be published?

2.

You can find it now @ http://www.espace.com.eg/neverblock/blog/2008/08/21/fiber-pooling-with-neverblock/

3.

I noticed something subtle - your first example will actually resume 4 times? returning 0,1,2,3 respectively 3 == 3.times {} the 4th resume reenters after the yield, finished the 3.times block and returns the last value - in this case 3... likewise the other examples will resume a 4th time returning 3. anyways - it's a tiny thing - neverblock is a great piece of work!

4.

A great primer on a new feature. Thanks for sharing it with the community!

5.

@Darragh, you are quite right, the last resume will return the x.times value, which is x