1. Technology
You can opt-out at any time. Please refer to our privacy policy for contact information.

Fibers

By

Ruby 1.9 adds another threading model to the mix. Thus far, you only had processes, which had their own address space and Ruby interpreter and threads, which shared a process and address space. Both of these can be a bit heavy, especially if you've delegated work to a large number of processes or threads. You'll quickly find yourself running out of memory and the time to create new threads or processes will grow (sometimes exponentially).

What Are Fibers?

Fibers are lighter than threads. A fiber is a bit like a method, but instead of being run in its entirety when called, a Fiber will run until it yields a value. At this point, it will save its internal state and suspend itself and control will return to the caller. While this doesn't introduce any concurrency, it does introduce another decoupling mechanism, allowing you to write small and reusable pieces of code.

Fiber Code

In the following code, a method is defined that will return a Fiber. This Fiber opens a file, and each time it's continued, it will read a line from a file and split it. As soon as it yields its value, it will suspend itself until the outside loop resumes it yet again.

The code in the Fiber is said to be decoupled from the rest of the code. It doesn't rely on any other code and it's easy to reuse. Decoupled code is also easier to test independently of other code. In other words, decoupling is a good idea, and Fiber is a way to decouple your code.

 #!/usr/bin/env ruby19
 
 def read_netlist(file)
   Fiber.new do
     f = File.open( file, 'r' )
 
     until f.eof
       Fiber.yield( f.read.split(/ /) )
     end
   end
 end
 
 fib = read_netlist('netlist.txt')
 
 while true do
   puts fib.resume
 end
 
See More About
  1. About.com
  2. Technology
  3. Ruby
  4. Beginning Ruby
  5. New in Ruby 1.9.x
  6. Fibers

©2014 About.com. All rights reserved.