note 127846 added to language.fibers
| From: | nesk at xakep dot ru | Date: | Mon, 24 Oct 2022 01:21:32 +0000 |
| Subject: | note 127846 added to language.fibers | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-219798@lists.php.net to get a copy of this message | ||
I think that in some cases it makes sense to convert a Fiber to a Generator (Coroutine) for
convenience. In such cases, this code will be useful:
<?php
function fiber_to_coroutine(\Fiber $fiber): \Generator
{
$index = -1; // Note: Pre-increment is faster than post-increment.
$value = null;
// Allow an already running fiber.
if (!$fiber->isStarted()) {
$value = yield ++$index => $fiber->start();
}
// A Fiber without suspends should return the result immediately.
if (!$fiber->isTerminated()) {
while (true) {
$value = $fiber->resume($value);
// The last call to "resume()" moves the execution of the
// Fiber to the "return" stmt.
//
// So the "yield" is not needed. Skip this step and return
// the result.
if ($fiber->isTerminated()) {
break;
}
$value = yield ++$index => $value;
}
}
return $fiber->getReturn();
}
?>
----
Server IP: 45.112.84.4
Probable Submitter: 45.91.159.161 (proxied: 2a00:1370:818a:2bcc:a1fe:9501:aed7:bbe5)
----
Manual Page -- https://php.net/manual/en/language.fibers.php
Edit -- https://main.php.net/note/edit/127846
Del: integrated -- https://main.php.net/note/delete/127846/integrated
Del: useless -- https://main.php.net/note/delete/127846/useless
Del: bad code -- https://main.php.net/note/delete/127846/bad+code
Del: spam -- https://main.php.net/note/delete/127846/spam
Del: non-english -- https://main.php.net/note/delete/127846/non-english
Del: in docs -- https://main.php.net/note/delete/127846/in+docs
Del: other reasons-- https://main.php.net/note/delete/127846
Reject -- https://main.php.net/note/reject/127846
Search -- https://main.php.net/manage/user-notes.php