Fibers
Cooperative concurrency.
What Is a Fiber?
A Fiber is a lightweight unit of execution you control by hand. Unlike threads, a fiber never runs on its own; you explicitly hand control to it and it hands control back.
- This is called cooperative concurrency.
- Fibers are cheap to create and pause.
- They are the foundation of generators and async I/O in Ruby.
Creating and Resuming
Create a fiber with Fiber.new and start or continue it with resume. The block runs until it finishes or pauses.
fiber = Fiber.new do
puts "Inside the fiber"
end
fiber.resume
puts "Back in main"