Sobes.tech
Middle+

What is Fiber in Ruby?

sobes.tech AI

Answer from AI

Fiber in Ruby is a lightweight execution thread (coroutine) that allows creating multiple parallel execution threads within a single process / operating system thread. This enables managing the order of code execution by switching between Fibers without involving the OS scheduler.

Main characteristics of Fiber:

  • Cooperative Scheduling: Fibers are not preempted by the OS kernel. Switching between them is explicit using resume and yield methods.
  • Single Thread: All Fibers run sequentially in one thread, but switching between them creates an illusion of parallelism for the code inside the thread.
  • State Preservation: Fiber remembers its state (local variables, execution point) when yield is called and resumes from that point when resume is called.

Applications of Fiber:

  • Implementing asynchronous code: Modeling non-blocking operations without using callbacks or complex constructs.
  • Iterators and generators: Creating complex iterators that generate values on demand.
  • Finite automata processing: Modeling states and transitions explicitly.

Example of usage:

# Creating a Fiber
fiber = Fiber.new do
  puts "Hello from Fiber 1"
  value1 = Fiber.yield(1) # Pause execution, return 1
  puts "Received from Fiber 1: #{value1}"

  puts "Hello from Fiber 2"
  value2 = Fiber.yield(2) # Pause execution, return 2
  puts "Received from Fiber 2: #{value2}"

  puts "Hello from Fiber 3"
  3 # End of Fiber, return 3
end

puts "Main: Before first resume"
result1 = fiber.resume # Resume Fiber execution
puts "Main: Received from Fiber: #{result1}"

puts "Main: Before second resume"
result2 = fiber.resume("from Main 1") # Resume and pass value
puts "Main: Received from Fiber: #{result2}"

puts "Main: Before third resume"
result3 = fiber.resume("from Main 2") # Resume and pass value
puts "Main: Received from Fiber: #{result3}"

Main methods:

  • Fiber.new { ... }: Creates a new Fiber. The code block runs on the first resume call.
  • fiber.resume(*args): Resumes Fiber execution. Arguments passed to resume become the return value of Fiber.yield or the arguments of the launching block.
  • Fiber.yield(*args): Pauses the current Fiber and returns control to the code that started it (resume). Arguments passed to yield become the return value of resume.
  • Fiber.current: Returns the current Fiber.

Difference between Fiber and Thread:

Attribute Fiber Thread
Scheduling Cooperative (explicit switching) Preemptive (OS-managed)
Resources Lightweight (less resource-intensive) Heavier (more resource-intensive)
Parallelism Mock parallelism within a single thread True parallelism (uses CPU cores)
Communication Via yield and resume Via shared memory, message passing, etc.
Debugging Relatively simpler (linear flow) More complex (race conditions, locks)

Fibers provide a lower-level execution management mechanism compared to Threads, requiring explicit control of switches.