Type:
Class

Fibers are primitives for implementing light weight cooperative concurrency in Ruby. Basically they are a means of creating code blocks that can be paused and resumed, much like threads. The main difference is that they are never preempted and that the scheduling must be done by the programmer and not the VM.

As opposed to other stackless light weight concurrency models, each fiber comes with a small 4KB stack. This enables the fiber to be paused from deeply nested function calls within the fiber block.

When a fiber is created it will not run automatically. Rather it must be be explicitly asked to run using the Fiber#resume method. The code running inside the fiber can give up control by calling Fiber.yield in which case it yields control back to caller (the caller of the Fiber#resume).

Upon yielding or termination the Fiber returns the value of the last executed expression

For instance:

fiber = Fiber.new do
  Fiber.yield 1
  2
end

puts fiber.resume
puts fiber.resume
puts fiber.resume

produces

1
2
FiberError: dead fiber called

The Fiber#resume method accepts an arbitrary number of parameters, if it is the first call to resume then they will be passed as block arguments. Otherwise they will be the return value of the call to Fiber.yield

Example:

fiber = Fiber.new do |first|
  second = Fiber.yield first + 2
end

puts fiber.resume 10
puts fiber.resume 14
puts fiber.resume 18

produces

12
14
FiberError: dead fiber called
transfer

fiber.transfer(args, ...) â obj Instance Public methods Transfer control to

2015-04-05 19:10:41
current

Fiber.current() â fiber Class Public methods Returns the current fiber. You

2015-04-05 18:50:21
alive?

fiber.alive? â true or false Instance Public methods Returns true if the fiber

2015-04-05 19:00:15
yield

Fiber.yield(args, ...) â obj Class Public methods Yields control back to the

2015-04-05 18:54:59
resume

fiber.resume(args, ...) â obj Instance Public methods Resumes the fiber from

2015-04-05 19:07:13