Fibers and the scheduler

Fiber.new and resume

A fiber is a block with its own stack that runs until it yields and continues where it stopped. It is cooperative: nothing runs until the program calls resume:

ruby -e 'f = Fiber.new { Fiber.yield 1; 2 }; p f.resume, f.resume'

1
2

The first resume runs to the yield and returns 1; the second continues after it and returns 2. A third resume raises FiberError, because the block has finished.

Fiber.yield with a value

Both directions carry a value: resume(x) is the result of the Fiber.yield inside, and the value passed to yield is the result of the resume outside:

ruby -e 'f = Fiber.new { |x| y = Fiber.yield(x + 1); y * 2 }; p f.resume(1); p f.resume(5)'

2
10

That two-way hand-off is what an Enumerator uses internally and what a generator is built from. A fiber is not a thread: only one of them runs at a time, and the switch happens at an explicit yield.

The scheduler

Ruby 3 added a fiber scheduler: a class that the program registers, and the runtime calls it when a fiber blocks on I/O. The sketch below shows the three methods a description usually starts with, and Ruby names the rest when the scheduler is installed:

class Scheduler def fiber(&block) Fiber.new(blocking: false, &block) end def io_wait(io, events, timeout = nil) # wait for the socket, then return the events that are ready end def kernel_sleep(duration = nil) # suspend this fiber and resume it after the duration end end Fiber.set_scheduler(Scheduler.new)

ruby scheduler.rb

scheduler.rb:15:in 'Fiber.set_scheduler': Scheduler must implement #block (ArgumentError)

Fiber.set_scheduler(Scheduler.new)
                    ^^^^^^^^^^^^^
    from scheduler.rb:15:in '<main>'

A scheduler must also answer block and unblock, so the four required methods are io_wait, kernel_sleep, block and unblock; fiber is optional and Ruby supplies a default. With a scheduler installed, sleep and a socket read suspend the fiber instead of the thread, and one thread can hold thousands of waiting connections. The async gem is a scheduler with a production implementation; the standard library ships only the interface.

When a fiber helps

A fiber does not use a second core and does not make a CPU loop faster. For arithmetic, threads and processes are the previous lessons; a fiber is for code that waits.

What to watch for

A fiber that never yields blocks its thread exactly like a method. The scheduler only helps at the calls it knows: I/O and sleep. A long computation inside a fiber still stops everything.

Fibers in one thread share the same mutable state with no lock. A fiber switch can happen in the middle of an update, so the mutex rules from the thread lesson apply; the scheduler makes the bug less frequent, not impossible.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. How does a fiber hand control back to the code that resumed it?

    Answer

    It calls Fiber.yield, and nothing else takes the control away from it

    A fiber is cooperative: it runs until it yields or finishes, so a long computation inside it holds the thread.

  2. What does this program print? f = Fiber.new { Fiber.yield 1; 2 } p f.resume p f.resume

    Answer

    1 / 2

    The first resume runs to the yield and returns its value; the second continues after it to the end of the block.

  3. What does this program print? f = Fiber.new { |x| y = Fiber.yield(x + 1); y * 2 } p f.resume(1) p f.resume(5)

    Answer

    2 / 10

    The argument of resume is the value of the yield inside, and the value of yield is the result of resume outside.

  4. What does this program print? f = Fiber.new { 1 } f.resume begin f.resume rescue FiberError => e puts e.class end

    Answer

    FiberError

    The block has finished, so there is nothing left to resume and Ruby raises FiberError.

  5. What does this program print? f = Fiber.new do i = 0 loop { Fiber.yield i; i += 1 } end p f.resume p f.resume p f.resume

    Answer

    0 / 1 / 2

    Each resume continues after the previous yield, and the counter grows by one between them.

  6. What does Fiber.yield 1 do when it runs outside any fiber?

    Answer

    It raises FiberError, because the root fiber cannot yield

    Only a fiber created with Fiber.new can suspend itself, so a yield at the top level is an error.

  7. Which methods must a class implement to be accepted by Fiber.set_scheduler?

    Answer

    io_wait, kernel_sleep, block and unblock; fiber is optional

    Ruby checks the four when the scheduler is installed and names the first missing one, which is why a three-method sketch is refused.

  8. What does a fiber do for a CPU-bound loop?

    Answer

    Nothing: it does not add a core, and the loop still holds its thread

    A fiber is a way to write waiting code as straight code; for arithmetic the tools are threads and processes, and even threads share one core under the GVL.

  9. What does this program print? f = Fiber.new do |first| second = Fiber.yield(first + 1) second * 10 end p f.resume(1) p f.resume(2)

    Answer

    2 / 20

    The first resume returns the value of the yield, and the second passes 2 into the fiber, which multiplies it by ten.

  10. For which job is a fiber the right tool?

    Answer

    Thousands of sockets that mostly wait, with little CPU work

    The scheduler turns waiting into a fiber switch, which is what a crawler or an HTTP client with many connections needs.

Article author: Arthur Isaev