note 126409 added to class.parallel-channel
| From: | gam6itko at main dot php dot net | Date: | Fri, 10 Sep 2021 13:59:53 +0000 |
| Subject: | note 126409 added to class.parallel-channel | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-216943@lists.php.net to get a copy of this message | ||
<?php
// the very weird way to calculate factorial ^_^
// we create one thread and synching them with buffered channel
// at fact only one thread is executing at the time
use parallel\{Channel, Future, Runtime};
for ($n = 0; $n <= 10; $n++) {
echo "!$n = " . factorial($n) . PHP_EOL;
}
/**
* Creates $n threads.
*/
function factorial(int $n): int
{
// buffered channel - using for sync threads ^_^
$channel = new Channel(1);
$futureList = [];
for ($i = 2; $i <= $n; $i++) {
$runtime = new Runtime();
$futureList[] = $runtime->run(
static function (Channel $channel, $multiplier): void {
$f = $channel->recv();
$channel->send($f * $multiplier);
},
[$channel, $i]
);
}
$channel->send(1);
// waiting until all threads are done
do {
$allDone = array_reduce(
$futureList,
function (bool $c, Future $future): bool {
return $c && $future->done();
},
true
);
} while (false === $allDone);
return $channel->recv();
}
// output:
// !0 = 1
// !1 = 1
// !2 = 2
// !3 = 6
// !4 = 24
// !5 = 120
// !6 = 720
// !7 = 5040
// !8 = 40320
// !9 = 362880
// !10 = 3628800
----
Server IP: 45.112.84.4
Probable Submitter: 45.112.85.242 (proxied: 176.104.221.149)
----
Manual Page -- https://php.net/manual/en/class.parallel-channel.php
Edit -- https://main.php.net/note/edit/126409
Del: integrated -- https://main.php.net/note/delete/126409/integrated
Del: useless -- https://main.php.net/note/delete/126409/useless
Del: bad code -- https://main.php.net/note/delete/126409/bad+code
Del: spam -- https://main.php.net/note/delete/126409/spam
Del: non-english -- https://main.php.net/note/delete/126409/non-english
Del: in docs -- https://main.php.net/note/delete/126409/in+docs
Del: other reasons-- https://main.php.net/note/delete/126409
Reject -- https://main.php.net/note/reject/126409
Search -- https://main.php.net/manage/user-notes.php