0
0
Rubyprogramming~5 mins

Fiber for cooperative concurrency in Ruby

Choose your learning style9 modes available
Introduction

Fibers let your program do many things by switching tasks yourself. They help you manage multiple jobs without waiting for one to finish first.

When you want to run small tasks one after another without blocking the whole program.
When you need to pause a task and come back to it later.
When you want to write code that looks simple but handles multiple jobs cooperatively.
When you want to avoid complex thread management but still do multitasking.
Syntax
Ruby
fiber = Fiber.new do
  # code to run inside fiber
  Fiber.yield # pause and return control
  # resume here
end

fiber.resume # start or continue fiber

Fiber.new creates a new fiber with a block of code.

Fiber.yield pauses the fiber and returns control to where resume was called.

Examples
This fiber prints "Hello", pauses, then prints "World" when resumed again.
Ruby
fiber = Fiber.new do
  puts "Hello"
  Fiber.yield
  puts "World"
end

fiber.resume  # prints Hello
fiber.resume  # prints World
This fiber runs three steps, pausing after each one until resumed.
Ruby
fiber = Fiber.new do
  3.times do |i|
    puts "Step #{i + 1}"
    Fiber.yield
  end
end

3.times { fiber.resume }
Sample Program

This program shows how a fiber pauses and resumes. It prints messages before, during, and after the fiber runs.

Ruby
fiber = Fiber.new do
  puts "Start task"
  Fiber.yield
  puts "Resume task"
  Fiber.yield
  puts "End task"
end

puts "Before first resume"
fiber.resume
puts "Between resumes"
fiber.resume
puts "After last resume"
fiber.resume
OutputSuccess
Important Notes

Fibers are not threads; they run one at a time and switch only when you tell them.

Use fibers to simplify code that needs to pause and continue later.

Calling resume on a finished fiber will raise an error.

Summary

Fibers let you pause and resume tasks manually.

They help run multiple jobs cooperatively without real parallelism.

Use Fiber.new, Fiber.yield, and resume to control execution.