note 129789 added to parallel-events.poll
| From: | thierry@pielo.net | Date: | Wed, 02 Oct 2024 20:35:13 +0000 |
| Subject: | note 129789 added to parallel-events.poll | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-221574@lists.php.net to get a copy of this message | ||
<?php
/**
* Fibonacci
* Mimics the Go "select" statement with event-loop
* Variant with non-blocking loop and $events->poll()
*
* Adapted from https://go.dev/tour/concurrency/5
*/
use \parallel\{Channel,Events,Events\Event,Events\Input};
function fibonacci (Channel $channel, Channel $quit) {
$x = 0;
$y = 1;
$events = new Events();
$events->addChannel($channel);
$events->addChannel($quit);
$input = new Input();
$input->add('fibonacci', $x);
$events->setInput($input);
$events->setBlocking(false);
while (true) {
if ($event = $events->poll()) {
switch ($event->source) {
case 'fibonacci':
if ($event->type == Event\Type::Write) {
$c = $x;
$x = $y;
$y += $c;
// Channel and Input got removed, add them again
$events->addChannel($channel);
$input->add('fibonacci', $x);
$events->setInput($input);
}
break;
case 'quit':
echo "quit\n";
return;
}
}
}
}
$channel = Channel::make('fibonacci', 1);
$quit = Channel::make('quit');
\parallel\run(function (Channel $channel, Channel $quit) {
for ($i=0; $i < 10; $i++) {
$e = $channel->recv();
echo "$e\n";
}
$quit->send(0);
}, [$channel, $quit]);
fibonacci($channel, $quit);
?>
// Produces
0
1
1
2
3
5
8
13
21
34
quit
----
Server IP: 45.112.84.4
Probable Submitter: 80.90.5.137 (proxied: 77.141.36.104)
----
Manual Page -- https://php.net/manual/en/parallel-events.poll.php
Edit -- https://main.php.net/note/edit/129789
Del: integrated -- https://main.php.net/note/delete/129789/integrated
Del: useless -- https://main.php.net/note/delete/129789/useless
Del: bad code -- https://main.php.net/note/delete/129789/bad+code
Del: spam -- https://main.php.net/note/delete/129789/spam
Del: non-english -- https://main.php.net/note/delete/129789/non-english
Del: in docs -- https://main.php.net/note/delete/129789/in+docs
Del: other reasons-- https://main.php.net/note/delete/129789
Reject -- https://main.php.net/note/reject/129789
Search -- https://main.php.net/manage/user-notes.php