Lab 03: Fiber Internals

Time: 60 minutes | Level: Architect | Docker: docker run -it --rm php:8.3-cli bash

Overview

PHP 8.1 introduced Fibers—lightweight coroutines that enable cooperative multitasking without threads. This lab covers Fiber internals, building a cooperative scheduler from scratch, combining Fibers with Generators, and simulating async I/O.


Step 1: Fiber Fundamentals

A Fiber is a stackful coroutine: it has its own call stack and can suspend/resume at any point.

Main thread

    ├─→ Fiber::start()  ──────────────────────→ [Fiber executes]
    │                                                   │
    │   Fiber::suspend($value) ←────────────────────────┘
    │   (main receives $value via getReturn() or resume())

    ├─→ Fiber::resume($input) ───────────────→ [Fiber continues]

    └─→ [Fiber returns / terminates]
<?php
// Basic Fiber lifecycle
$fiber = new Fiber(function(): string {
    echo "Fiber: starting\n";
    
    $input = Fiber::suspend('first yield');
    echo "Fiber: received '$input'\n";
    
    $input2 = Fiber::suspend('second yield');
    echo "Fiber: received '$input2'\n";
    
    return 'fiber done';
});

echo "Main: before start\n";
$val1 = $fiber->start();            // starts fiber, gets first suspended value
echo "Main: fiber yielded '$val1'\n";

$val2 = $fiber->resume('hello');    // resumes fiber with value
echo "Main: fiber yielded '$val2'\n";

$fiber->resume('world');            // fiber completes
echo "Main: fiber return = '" . $fiber->getReturn() . "'\n";
echo "Main: fiber terminated = " . ($fiber->isTerminated() ? 'yes' : 'no') . "\n";

📸 Verified Output:


Step 2: Fiber State Machine

💡 Fiber::getCurrent() returns the currently running Fiber (or null if in main context). Useful for detecting if code is running inside a Fiber.


Step 3: Cooperative Scheduler — Round Robin

📸 Verified Output:

💡 This is exactly how event loops like ReactPHP and Amp work internally. The scheduler drives all fibers cooperatively—no OS threads, single process.


Step 4: Priority Scheduler


Step 5: Fiber + Generator Combination

📸 Verified Output:


Step 6: Async HTTP Simulation


Step 7: Fiber Error Handling

📸 Verified Output:


Step 8: Capstone — Full Cooperative Scheduler with I/O Simulation

📸 Verified Output:


Summary

Feature
API
Use Case

Create fiber

new Fiber(callable)

Define a coroutine

Start fiber

$fiber->start($arg)

First execution, get first suspended value

Suspend fiber

Fiber::suspend($val)

Yield control back to caller

Resume fiber

$fiber->resume($val)

Continue from suspension

Inject exception

$fiber->throw($e)

Error injection into suspended fiber

State check

isStarted/isSuspended/isRunning/isTerminated

Lifecycle management

Current fiber

Fiber::getCurrent()

Detect fiber context

Return value

$fiber->getReturn()

Get final return value

Fiber + Generator

Fiber wraps Generator

Async + lazy evaluation

Cooperative scheduling

Round-robin loop

Single-thread concurrency

Last updated