CodeBlanks Logo Icon CodeBlanks

Fibers

PHP course · Expert · Lesson 40/54

Learn to write thread-like coroutines with the Fiber class.

What is a Fiber?

PHP 8.1 added the Fiber class: a coroutine, a thread-like unit of cooperative execution. It is a piece of code that can pause and resume within the same call stack.

Create one with new Fiber(fn). The ->start() method runs it; Fiber::suspend() pauses and returns to the caller; ->resume() continues.

Fibers are not OS threads; they enable cooperative multitasking. No other fiber runs unless the current one pauses.

Data between suspend and resume

Inside a fiber, Fiber::suspend($v) halts execution and returns $v to the start() call. The caller resumes with ->resume($w); $w becomes the result of suspend().

This builds a two-way value flow between the fiber and the caller. When the fiber completes, getReturn() reads its return value.

Typical uses: asynchronous I/O, producer-consumer patterns and event loop implementations.

Exercise A basic Fiber flow

Create a Fiber: when started it should print fiber-start, pause with Fiber::suspend(), then print fiber-end after resume.

Outside, call start(), print main1, call resume(), print main2. Output order should be fiber-start, main1, fiber-end, main2.

Show example solution
$f = new Fiber(function (): void {
  echo "fiber-start\n";
  Fiber::suspend();
  echo "fiber-end\n";
});

$f->start();
echo "main1\n";
$f->resume();
echo "main2\n";

Test yourself

  1. Which method starts a Fiber?

    • run()
    • begin()
    • start()
    • launch()
    Show answer

    start() — Correct. The start() method of the Fiber class begins the fiber and sends the initial value.

  2. Fiber suspend call

    $f = new Fiber(function ($n) {
      echo $n;
      ____($n + 1);
    });
    
    Show answer
    $f = new Fiber(function ($n) {
      echo $n;
      Fiber::suspend($n + 1);
    });
    
  3. Match the Fiber concepts

    Fiber
    coroutine class
    start
    begins the fiber
    suspend
    pauses the fiber
    resume
    continues a paused fiber

All lessons in Expert