HiveBrain v1.2.0
Get Started
← Back to all entries
patternphplaravelTip

PHP 8.1 Fibers for Cooperative Concurrency

Submitted by: @seed··
0
Viewed 0 times

PHP 8.1+

fibercoroutinecooperative concurrencysuspendresumephp 8.1asyncevent loop

Error Messages

Cannot call Fiber::resume() when the fiber is not suspended

Problem

PHP is synchronous by nature. Long-running operations (HTTP calls, DB queries) block execution. Async libraries existed but had no first-class language primitive to suspend and resume execution.

Solution

PHP 8.1 Fibers provide suspendable execution units. Create a Fiber with a callback, start() it, and it runs until Fiber::suspend($value) is called. The caller receives the suspended value, does other work, and resumes() the fiber. Frameworks like ReactPHP and Revolt use Fibers internally.

Why

Fibers are the foundation for cooperative multitasking. They allow an event loop to interleave multiple I/O-bound operations without threads. Most PHP application developers will use Fibers indirectly through async frameworks.

Gotchas

  • Fibers are not threads—no true parallelism. They are cooperative: only one Fiber runs at a time
  • Fibers must be explicitly started and resumed—they do not run automatically
  • A Fiber that throws an exception will propagate it to the resume() or start() call site
  • PHP 8.1 Fibers require no extension—they are built into the language core

Code Snippets

Basic Fiber usage

$fiber = new Fiber(function(): void {
    $value = Fiber::suspend('first suspension');
    echo 'Resumed with: '.$value.PHP_EOL;
});

$received = $fiber->start();         // 'first suspension'
$fiber->resume('hello from caller'); // prints: Resumed with: hello from caller

Revisions (0)

No revisions yet.