Skip to Content
Course content

33: Fibers for Lightweight Concurrency

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I've talked to plenty of developers who see "Fibers" in the PHP 8.1+ documentation and immediately think, "Great, I can finally do true multithreading in PHP." They assume that by wrapping code in a Fiber, the CPU will suddenly start splitting tasks across multiple cores, allowing two heavy loops to run at the exact same time.

The "Parallelism" Myth vs. Cooperative Multitasking

Here is the hard truth: Fibers do not provide parallelism. If you start two Fibers and each one contains a while loop that calculates prime numbers for ten seconds, your script will still take twenty seconds to finish. PHP is still single-threaded.

// This will NOT run in parallel
$fiber1 = new Fiber(function() {
    for ($i = 0; $i < 1000000000; $i++) {} 
    echo "Fiber 1 done\n";
});

$fiber2 = new Fiber(function() {
    for ($i = 0; $i < 1000000000; $i++) {} 
    echo "Fiber 2 done\n";
});

$fiber1->start();
$fiber2->start();
// You'll wait for 1 to finish entirely before 2 even starts.

So, what are they actually for? Fibers are about cooperative concurrency. Instead of the operating system forcing a thread to stop (preemptive multitasking), the code itself decides when to "pause" and hand control back to the main program. It's less about doing two things at once and more about not sitting around doing nothing while you wait for a slow network response or a file read.

Stopping the Clock with Suspend and Resume

The real power of a Fiber is the ability to pause its entire execution state—including the call stack and local variables—and jump back to where you were later. I like to think of it as a "bookmark" for your code.

Imagine you're building a system that fetches data from three different APIs. Normally, you'd wait for API A, then B, then C. With Fibers, you can start the request for A, Fiber::suspend() it to let the program do other work, and then resume() it once the socket actually has data ready to read.

$fiber = new Fiber(function(): void {
    echo "Starting API request...\n";
    // We simulate a non-blocking I/O wait here
    Fiber::suspend('waiting_for_network'); 
    echo "Processing API response!\n";
});

$value = $fiber->start(); 
echo "The fiber said: " . $value . "\n"; // Output: waiting_for_network

// ... Imagine we do other work here, like logging or handling other requests ...

echo "Now we resume.\n";
$fiber->resume();

In the example above, the Fiber didn't finish. It stopped mid-function, remembered exactly where it was, and gave control back to the main script. When we called resume(), it didn't start over from the top; it woke up exactly where Fiber::suspend() was called.

Orchestrating Work with a Simple Scheduler

On their own, Fibers are just low-level primitives. You rarely use them raw in a production app; instead, you use a library like Amp or ReactPHP. But to understand how those libraries work, you need to understand the "Scheduler" pattern. A scheduler is just a loop that keeps track of all active Fibers and resumes them when they are ready to move forward.

I've found that the best way to wrap your head around this is to imagine a "Task Manager" that polls different jobs. If a job is suspended, the manager moves to the next one. This prevents one slow I/O operation from freezing your entire server process.

$tasks = [
    new Fiber(fn() => print("Task A started\n" . Fiber::suspend() . " Task A finished\n")),
    new Fiber(fn() => print("Task B started\n" . Fiber::suspend() . " Task B finished\n")),
];

// Start them all
foreach ($tasks as $task) {
    $task->start();
}

// In a real app, we'd check if the socket is readable here.
// For this demo, we just resume them manually.
foreach ($tasks as $task) {
    $task->resume(" [Data Received] ");
}

Notice how the output is interleaved? "Task A started", "Task B started", and then the finishes. We've effectively managed multiple execution contexts without ever needing multiple CPU threads.




📋 Practical Task

Build a Cooperative Mock-API Aggregator

Your goal is to simulate a scenario where you are fetching data from three different "slow" sources without blocking the entire script execution linearly. Since we don't have a real asynchronous event loop here, you will simulate the "ready" state of the APIs.

Requirements:

  • Create three separate Fiber instances. Each should represent a request to a different service (e.g., "User Service", "Order Service", "Payment Service").
  • Inside each Fiber, print a message saying the request has started, then call Fiber::suspend(), passing a string identifying which service is waiting.
  • After the suspension, the Fiber should print a message saying the data has been "received" and return a mock data array.
  • Implement a while loop in your main script that keeps track of these Fibers. The loop should continue as long as there are Fibers that have not yet terminated (use $fiber->isTerminated()).
  • Inside the loop, iterate through your list of Fibers and resume() them.

Expected Behavior: Your console should show all three services "starting" before any of them "finish," demonstrating that the execution is jumping between contexts rather than finishing one service entirely before moving to the next.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.