note 124623 added to class.parallel-channel

From: Date: Thu, 16 Jan 2020 18:00:26 +0000
Subject: note 124623 added to class.parallel-channel
Groups: php.notes 
Request: Send a blank email to php-notes+get-213891@lists.php.net to get a copy of this message
This is an example of using a channel to produce data for consumers. In this example, the producer Runtime instance will send the time in seconds in which the consumers shall sleep. <?php use parallel\{Runtime, Channel}; main($argv); function main(array $argv) { if (count($argv) !== 3) { echo "Type: hello-parallel.php <number-of-tasks> <maximum-time-of-sleep (in seconds)>" . PHP_EOL; echo "Example: hello-parallel.php 5 3" . PHP_EOL; die; } else { $numberOfTasks = intval($argv[1]); $maximumTimeOfSleep = intval($argv[2]); $t1 = microtime(true); parallelize($numberOfTasks, $maximumTimeOfSleep); $endTime = microtime(true) - $t1; echo PHP_EOL."Finished $numberOfTasks task(s) in {$endTime}s".PHP_EOL; } } function parallelize(int $numberOfTasks, int $maximumTimeOfSleep) { $channel = new Channel(); $taskIds = array_map(function () use ($maximumTimeOfSleep) { return $id = uniqid("task::"); }, range(0, $numberOfTasks - 1)); $timesToSleep = array_map(function () use ($maximumTimeOfSleep) { return rand(1, $maximumTimeOfSleep); }, $taskIds); $producer = new Runtime(); $producerFuture = $producer->run(function (Channel $channel, array $timesToSleep) { foreach ($timesToSleep as $timeToSleep) { $channel->send($timeToSleep); } }, [$channel, $timesToSleep]); $consumerFutures = array_map(function (string $id) use ($channel) { $runtime = new Runtime(); return $runtime->run(function (string $id, Channel $channel) { $timeToSleep = $channel->recv(); echo "Hello from $id. I will sleep for $timeToSleep second(s).".PHP_EOL; sleep($timeToSleep); echo "$id slept for $timeToSleep second(s).".PHP_EOL; return $timeToSleep; }, [$id, $channel]); }, $taskIds); wait($consumerFutures); wait([$producerFuture]); } function wait(array $futures) { return array_map(function ($future) { return $future->value(); }, $futures); } ---- Server IP: 45.112.84.4 Probable Submitter: 38.142.137.34 (proxied: 201.76.114.93) ---- Manual Page -- http://php.net/manual/en/class.parallel-channel.php Edit -- https://master.php.net/note/edit/124623 Del: integrated -- https://master.php.net/note/delete/124623/integrated Del: useless -- https://master.php.net/note/delete/124623/useless Del: bad code -- https://master.php.net/note/delete/124623/bad+code Del: spam -- https://master.php.net/note/delete/124623/spam Del: non-english -- https://master.php.net/note/delete/124623/non-english Del: in docs -- https://master.php.net/note/delete/124623/in+docs Del: other reasons-- https://master.php.net/note/delete/124623 Reject -- https://master.php.net/note/reject/124623 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#213891) next »