Coroutines vs Fibers in PHP: Which Concurrency Model Wins?
This article explains the fundamental differences between coroutines and fibers in modern PHP, covering their concepts, implementation layers, scheduling, stack management, integration, and practical code examples, helping developers choose the right concurrency approach for high‑performance applications.
In modern PHP development, especially for high‑concurrency, high‑performance network applications, “coroutine” and “fiber” are two frequently mentioned but often confused concepts. Both aim to solve the performance bottleneck of traditional synchronous blocking I/O, yet they differ significantly in implementation level, control method, and use cases.
Core Concept Overview
Thread : Like a complete production line in a factory, scheduled by the operating system. Creation and switching are costly but can run in true parallel on multi‑core CPUs.
Coroutine : Like multiple workers on a single production line sharing resources. Workers cooperate and take turns; when one waits for I/O, it yields its position to another, maximizing line utilization. Implemented in user space with very low switching cost.
Fiber : A more low‑level or “enhanced” implementation of coroutines. It provides pre‑emptive switching that can occur at any function‑call depth. If coroutines are “cooperative” (requiring explicit yield), fibers give you a powerful “remote control” to interrupt and resume a call stack at will.
In the PHP world these concepts are realized as:
Coroutine : Mainly implemented via extensions such as Swoole or Swow, often combined with Generator and the yield keyword.
Fiber : Introduced as a core extension in PHP 8.1, bringing the fiber concept directly into the language.
Detailed Comparison: Coroutine vs. Fiber (in PHP)
Introduction version/method : Coroutines are simulated through third‑party extensions (e.g., Swoole) or the Generator feature introduced in PHP 5.5+. Fibers are built‑in as the core ext‑fiber extension starting with PHP 8.1.
Implementation level : Coroutines usually rely on Generators (user‑space) or custom schedulers in extensions. Fibers are provided directly by the PHP engine at the C level, closer to the virtual machine.
Switching method : Coroutines use cooperative switching; developers must explicitly call yield to yield execution. Fibers also use cooperative switching but are more flexible, allowing suspension via Fiber::suspend() at any call depth.
Scheduler : Coroutines depend on an external scheduler such as Swoole’s event loop. Fibers do not include a scheduler; they only offer suspend/resume primitives, leaving scheduling strategy to the developer, which makes them adaptable to any event loop.
Stack management : Generator‑based coroutines have a relatively simple stack context. Fibers maintain a full stack, enabling interruption of deep call chains and complete restoration upon resume.
Integration : Swoole provides a complete asynchronous programming solution (servers, timers, coroutine‑enabled clients) ready to use out of the box. Fibers expose low‑level primitives, requiring developers to build higher‑level abstractions or rely on frameworks like ReactPHP or AMP.
Learning curve / difficulty : Coroutines have a higher entry barrier but benefit from extensive ecosystem and well‑defined patterns. Fibers are conceptually lower‑level, demanding a deeper understanding of scheduling principles, which can increase implementation complexity.
Code Example: Feel the Difference
1. Coroutine based on Generator
This is the early PHP way to simulate coroutines, leveraging the Generator feature that can pause and resume execution.
<?php
function task1() {
for ($i = 1; $i <= 3; $i++) {
echo "Task 1: $i
";
yield; // explicitly yield control
}
}
function task2() {
for ($i = 1; $i <= 3; $i++) {
echo "Task 2: $i
";
yield; // explicitly yield control
}
}
$gen1 = task1();
$gen2 = task2();
// a simple "scheduler"
while ($gen1->valid() || $gen2->valid()) {
$gen1->valid() && $gen1->current() && $gen1->next();
$gen2->valid() && $gen2->current() && $gen2->next();
}Key point: you must call next() inside a loop (the scheduler) to resume execution, and yield must appear inside the generator function.
2. Fiber based
PHP 8.1’s Fiber is more flexible.
<?php
$fiber1 = new Fiber(function () {
echo "Fiber 1 started.
";
for ($i = 1; $i <= 3; $i++) {
echo "Fiber 1: $i
";
Fiber::suspend(); // suspend at any point
}
echo "Fiber 1 ended.
";
return 'Done 1';
});
$fiber2 = new Fiber(function () {
echo "Fiber 2 started.
";
for ($i = 1; $i <= 3; $i++) {
echo "Fiber 2: $i
";
Fiber::suspend();
}
echo "Fiber 2 ended.
";
return 'Done 2';
});
$fiber1->start();
$fiber2->start();
while (! $fiber1->isTerminated() || ! $fiber2->isTerminated()) {
if (! $fiber1->isTerminated()) {
$fiber1->resume();
}
if (! $fiber2->isTerminated()) {
$fiber2->resume();
}
}
echo $fiber1->getReturn(); // outputs: Done 1
echo $fiber2->getReturn(); // outputs: Done 2Key point: Fiber::suspend() can be called anywhere, even deep inside a call stack, preserving the full stack state.
Summary
Nature : Coroutines (Swoole style) are a complete high‑level asynchronous concurrency framework; Fibers (PHP Fiber) are a low‑level language feature for building concurrency primitives.
Advantages : Coroutines offer a mature ecosystem, full‑featured functionality, and excellent performance for building high‑throughput TCP/HTTP servers. Fibers provide a standardized, highly flexible foundation for future async libraries and custom scheduling strategies.
Applicable Scenarios : Use coroutines when you need to quickly develop high‑performance network services such as micro‑services, game servers, or real‑time communication. Use fibers when developing low‑level async libraries, integrating with existing event loops, or studying concurrency models.
In short, if you want ready‑to‑use business code with strong productivity, choose a coroutine framework like Swoole. If you are building libraries or need fine‑grained control over async components, dive into PHP Fibers. Modern frameworks (e.g., Hyperf) can combine both, offering unprecedented concurrency capabilities for PHP developers.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
