PHP Fibers — Cooperative Concurrency
PHP Fibers (introduced in PHP 8.1) bring cooperative multitasking to PHP. Unlike threads, Fibers are not truly parallel — they run cooperatively, switching control explicitly. They are the foundation for async PHP frameworks like ReactPHP and Amp v3.
<?php
$fiber = new Fiber(function(): string {
echo "Fiber started\n";
$value = Fiber::suspend('hello'); // pause, send 'hello' to caller
echo "Fiber resumed with: $value\n";
return 'fiber done';
});
$result1 = $fiber->start(); // starts fiber, runs until first suspend
echo "Main got: $result1\n"; // 'hello'
$result2 = $fiber->resume('world'); // resumes fiber with 'world'
echo "Fiber returned: " . $fiber->getReturn() . "\n";
Multiple Fibers — Simulated Concurrency
<?php
$fibers = [];
// Create 3 fibers that simulate async work
for ($i = 1; $i <= 3; $i++) {
$fibers[] = new Fiber(function() use ($i): void {
echo "Task $i: starting\n";
Fiber::suspend(); // yield control
echo "Task $i: step 2\n";
Fiber::suspend(); // yield again
echo "Task $i: done\n";
});
}
// Start all fibers
foreach ($fibers as $f) $f->start();
// Run until all complete (simple event loop)
do {
$running = false;
foreach ($fibers as $f) {
if ($f->isSuspended()) {
$f->resume();
$running = true;
}
}
} while ($running);
// Output: Task 1 starting, Task 2 starting, Task 3 starting,
// Task 1 step 2, Task 2 step 2... (interleaved!)
Fiber vs Generator
<?php
// Generator: one direction — only yields OUT
// Fiber: bidirectional — can suspend from ANYWHERE in the call stack
function deepFunction(): void {
// Can suspend from nested calls — impossible with generators!
Fiber::suspend('deep suspend');
}
$f = new Fiber(function(): void {
echo "Before\n";
deepFunction(); // suspends from inside nested function!
echo "After\n";
});
$val = $f->start(); // 'deep suspend'
$f->resume(); // continues after deepFunction()
Q: What is the difference between Fibers and threads?
Threads run truly in parallel (multiple CPU cores). Fibers are cooperative — only one runs at a time, and they must explicitly suspend to give control back. Fibers have no race conditions or mutex issues, making them simpler and safer. They enable concurrency (interleaving) but not parallelism.
Q: When would you use Fibers in real PHP code?
Directly, rarely. Fibers are primarily used by async frameworks (Amp, ReactPHP) under the hood to implement non-blocking I/O. You write coroutines using these frameworks, which use Fibers internally. Think of Fibers as the engine that makes async PHP work.
Comments (0)
No comments yet. Be the first!
Leave a Comment