Fibers
A fiber is a unit of work that can pause in the middle and resume later. Suspending hands control back to the code that started the fiber.
A fiber suspends with a value and resumes with one
start runs the fiber to its suspend line, and the suspend value prints. resume hands the word go in, and the fiber prints it and ends.
<?php
$fiber = new Fiber(function () {
$value = Fiber::suspend("ready");
echo "got ", $value, "\n";
return "done";
});
echo $fiber->start(), "\n";
$fiber->resume("go");
echo $fiber->getReturn(), "\n";Two fibers take turns by hand
Each fiber prints a start line and then suspends. The main code resumes them in the order it chooses, and each prints its end line.
<?php
$first = new Fiber(function () {
echo "first starts\n";
Fiber::suspend();
echo "first ends\n";
});
$second = new Fiber(function () {
echo "second starts\n";
Fiber::suspend();
echo "second ends\n";
});
$first->start();
$second->start();
$first->resume();
$second->resume();State checks give verdicts at fixed points
isStarted is false before start runs. isSuspended is true while the fiber waits, and isTerminated is true after the fiber ends.
<?php
$fiber = new Fiber(function () {
Fiber::suspend("pause");
});
var_dump($fiber->isStarted());
$fiber->start();
var_dump($fiber->isSuspended());
$fiber->resume();
var_dump($fiber->isTerminated());Example
<?php
$download = new Fiber(function () {
$step = Fiber::suspend("request sent");
echo "step: ", $step, "\n";
return "file saved";
});
echo $download->start(), "\n";
$download->resume("response in");
echo $download->getReturn(), "\n";Key points
- new Fiber builds a fiber from a function, but the function does not run yet.
- start runs the fiber until it suspends or ends, and it returns the suspend value.
- Fiber::suspend pauses the fiber and hands its value back to the caller.
- resume restarts a paused fiber and can hand a value in.
- The handed-in value becomes the value of the suspend line inside the fiber.
- getReturn reads what the fiber returned, once the fiber has ended.
In this example, the download fiber suspends at once with the words request sent. start prints that suspend value. resume hands in the words response in, and the fiber prints them as its next step. The fiber then returns file saved, and getReturn prints it.
Note
The program itself chooses every start and resume, so the print order is fixed.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
A resume call runs a fiber to its end. What does that resume call return?