<?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