Ruby Fibers provide a powerful mechanism for implementing lightweight, cooperative concurrency in Ruby programs. They offer a way to create small, independent units of execution that can be paused and resumed at will.
Fibers are primitives for implementing light-weight cooperative concurrency in Ruby. Unlike Ruby Threads, which are preemptively scheduled by the operating system, Fibers are cooperatively scheduled by the programmer. This allows for fine-grained control over execution flow.
To create a Fiber, use the Fiber.new
constructor with a block. The Fiber's execution begins when you call resume
on it. Here's a simple example:
fiber = Fiber.new do
puts "Inside the fiber"
Fiber.yield "Hello from fiber!"
puts "Fiber resumed"
end
puts fiber.resume
puts "Back in the main program"
puts fiber.resume
This code demonstrates the basic lifecycle of a Fiber: creation, initial resumption, yielding, and final resumption.
Fiber.yield
: Suspends the fiber's execution and returns control to the caller.fiber.resume
: Resumes the execution of the fiber from where it last yielded.Fiber.current
: Returns the currently executing fiber.Fibers are particularly useful in scenarios where you need fine-grained control over execution flow. Some common use cases include:
Here's an example of using a Fiber to create a simple generator that yields Fibonacci numbers:
fib = Fiber.new do
a, b = 0, 1
loop do
Fiber.yield a
a, b = b, a + b
end
end
10.times { puts fib.resume }
This Fiber generates Fibonacci numbers indefinitely, yielding each number in the sequence when resumed.
Ruby Fibers offer a powerful tool for implementing lightweight concurrency and managing complex control flows. By understanding their creation, resumption, and yielding mechanisms, you can leverage Fibers to write more efficient and elegant Ruby code for scenarios requiring fine-grained execution control.