Fibers: code that can pause
At the end of lesson 124 a narrator told its story in chapters: every resume ran the fiber up to the next Fiber.yield, and there it stopped – with all its local variables, right in the middle of the block – until the next resume. A Fiber is a piece of code with its own stack that you can pause and continue. Nobody interrupts it: it only stops where it says Fiber.yield itself. That's why it is called cooperative.
The values travel both ways. The argument of the first resume becomes the block's parameter; what Fiber.yield is given comes out of resume; and what the next resume is given comes out of Fiber.yield inside the fiber. Here a chef takes orders:
chef = Fiber.new do |order|
puts "chef got: #{order}"
order = Fiber.yield "#{order} is ready" # the fiber stops here
puts "chef got: #{order}"
"kitchen closed"
end
p chef.resume("bacon")
p chef.alive?
p chef.resume("eggs")
p chef.alive?
begin
chef.resume
rescue FiberError => error
error.message
endFollow the values: "bacon" went in as order, "bacon is ready" came out of the first resume. The second resume("eggs") woke the fiber up, and Fiber.yield returned "eggs". Then the block ran to its end, and its last value, "kitchen closed", was what resume returned. A fiber goes through four states: created (not yet started), resumed (running), suspended (waiting in a Fiber.yield) and terminated (the block is over). alive? is true until it is terminated – and a terminated fiber cannot be resumed again: FiberError.
You have used fibers already
In lesson 32 next fetched one value after the other from an Enumerator, even from an endless loop. How can a block stop in the middle of a loop and continue later? Exactly: next runs the block in a fiber, and y << value becomes a Fiber.yield value. peek looks at the next value without taking it:
tickets = Enumerator.new do |y|
number = 1
loop do
puts " (printing ticket #{number})"
y << "ticket #{number}"
number += 1
end
end
p tickets.next
p tickets.peek
p tickets.next
p tickets.next
here = Fiber.current
seen = nil
probe = Enumerator.new { |y| seen = Fiber.current; y << 1 }
probe.next
p seen == here # next: the block runs in a fiber of its own
probe.each { }
seen == here # each: right here, in the caller's fiberThe lines (printing ticket …) appear only when a value is wanted: the block runs just far enough for one ticket and pauses. peek printed ticket 2 already, so the next after it hands out the waiting ticket without printing. And Fiber.current shows where the block ran: under next in a fiber of its own (that's why it can pause), under each in the caller's – each runs the block in one go, from the beginning to the end. That is the difference between external iteration (the caller pulls, with next) and internal iteration (the block is pushed every value).
A scheduler: taking turns while waiting
Fibers are made for programs that wait a lot – for the network, a database, a file. Suppose every task is a fiber, and wherever it would wait, it pauses with Fiber.yield and says how long. A small loop, the scheduler, then always continues the fiber that wakes up first, and keeps a clock. Nothing really waits here – the clock just jumps ahead:
job = lambda do |name, waits|
Fiber.new do
waits.each do |seconds|
puts "#{name} waits #{seconds}s"
Fiber.yield seconds # it would wait here: wake me in that many seconds
end
"#{name} done"
end
end
# which fiber wants its next turn when
wake_at = { job.("bacon", [3, 1]) => 0, job.("eggs", [1, 1, 1]) => 0, job.("toast", [2]) => 0 }
clock = 0
until wake_at.empty?
fiber, clock = wake_at.min_by { |_, time| time } # who wakes up first?
print "#{clock}s: "
answer = fiber.resume
if fiber.alive?
wake_at[fiber] = clock + answer
else
puts answer
wake_at.delete(fiber)
end
end
clockThree tasks that wait 4, 3 and 2 seconds in all are done after 4 seconds instead of 9: while one waits, the others work. That is exactly how Thread and sleep work on this page: every simulated thread is a fiber, and sleep is a Fiber.yield to a scheduler like this one.
Real Ruby has this idea built in: the Fiber scheduler. With Fiber.set_scheduler you hand Ruby an object with methods such as io_wait, kernel_sleep and block/unblock. From then on, every non-blocking fiber (started with Fiber.schedule) that would wait for a socket, a file, sleep or a Queue calls the scheduler instead of blocking, and the scheduler resumes another fiber until the operating system reports that the data is there. The async gem is such a scheduler (with Async do … end): the code looks perfectly ordinary and sequential, yet thousands of downloads wait at the same time – in one thread, without a single Fiber.yield of your own. Falcon, a web server, is built on it.
Ractors: really in parallel
Fibers take turns; they never run at the same time. Threads in CRuby do not compute at the same time either: they share one lock, the GVL. Only a Ractor (from Ruby actor) computes on another processor core at the same time, because every Ractor has a lock of its own. The price is isolation: two Ractors must not share objects that can change – otherwise they would be writing into the same Array at the same time. They talk by sending messages, and they may only share objects that are shareable: numbers, symbols, nil, true, false, classes and modules, and anything frozen all the way down. Ractor.make_shareable freezes an object and everything inside it:
menu = Ractor.make_shareable({ "bacon" => ["crispy", "chewy"], "eggs" => ["fried"] })
p Ractor.shareable?(menu)
p menu["bacon"].frozen? # frozen all the way down
p Ractor.shareable?(42)
p Ractor.shareable?("toast")
begin
menu["bacon"] << "burnt"
rescue FrozenError => error
error.message
endA plain "toast" is not shareable, because a string can change; 42 is, because it never can. And once the menu is shareable, nobody can add "burnt" any more – not this program, and no Ractor either.
The Ractors themselves you can't start on this page: this Ruby runs as WebAssembly in a single thread, and Ractor.new raises a NotImplementedError. On your computer it works – with a warning that the Ractor API is still experimental. Ruby 4.0 reworked it: value waits for a Ractor and returns its block's last value (until Ruby 3.4 that was take), send (or <<) puts a message into a Ractor's inbox and Ractor.receive takes it out, and answers go back through a Ractor::Port, a mailbox you can hand to a Ractor (Ractor.yield is gone).
Save this as ractors.rb and run it with ruby ractors.rb – and watch your processor's load while the four Fibonacci numbers are computed.
# ractors.rb - ruby ractors.rb (Ruby 4.0)
def fib(n) = n < 2 ? n : fib(n - 1) + fib(n - 2)
# four Ractors compute at the same time, on four cores
workers = [30, 31, 32, 33].map { |n| Ractor.new(n) { |k| fib(k) } }
p workers.map(&:value) # wait for each one and take its result
port = Ractor::Port.new # a mailbox of our own, for the answers
shouter = Ractor.new(port) do |answers|
while (word = Ractor.receive) != :stop # takes the next message out of its inbox
answers << word.upcase
end
end
shouter.send("bacon") # puts a message into its inbox
p port.receive # => "BACON"
shouter.send(:stop)
word = "eggs"
Ractor.new { word } # ArgumentError: can not isolate a Proc ...The last line shows the isolation: a Ractor's block must not reach outside for word. Whatever it needs, it gets as an argument of Ractor.new or by message – a copy, unless the object is shareable, or moved with send(obj, move: true), after which the sender may no longer touch it. A rule of thumb: fibers for many tasks that mostly wait, threads for a few of them, and Ractors when the processor itself is the bottleneck.
take_turns(*fibers) resumes every fiber that is still alive once, in the order given, and goes round again and again until none is alive any more. It collects what every resume returns – the values passed to Fiber.yield and each fiber's last value – and returns the list. For the bacon and the coffee below that is ["bacon: sizzle", "coffee: grind", "bacon: flip", "coffee: ready", "bacon: crispy"]; without any fibers it is [].# def take_turns(*fibers)
# results = []
# ... # resume every fiber that is still alive, one after the other,
# ... # again and again until none is alive; keep what resume returns
# results
# end
bacon = Fiber.new do
Fiber.yield "bacon: sizzle"
Fiber.yield "bacon: flip"
"bacon: crispy"
end
coffee = Fiber.new do
Fiber.yield "coffee: grind"
"coffee: ready"
end
# take_turns(bacon, coffee)