note 126991 added to function.pcntl-fork

From: Date: Sun, 17 Apr 2022 14:53:26 +0000
Subject: note 126991 added to function.pcntl-fork
Groups: php.notes 
Request: Send a blank email to php-notes+get-218259@lists.php.net to get a copy of this message
<?php declare(strict_types = 1); /** * Helper method to execute a task */ function execute_task(int $task_id): void { echo 'Starting task: ' . $task_id . PHP_EOL; // Simulate doing actual work with sleep() $execution_time = rand(5, 10); sleep($execution_time); echo "Completed task: ${task_id}. Took ${execution_time} seconds.\n"; } /** * Builds a list of tasks */ function generator(): Generator { $item_count = 50; for ($i = 1; $i <= $item_count; $i++) { yield $i; } } /** * Starts the work */ function launch(): void { $processCount = 0; $status = null; echo 'Running as pid: ' . getmypid() . PHP_EOL; $taskList = generator(); do { echo 'Still tasks to do' . PHP_EOL; if ($processCount >= 5) { echo 'Waiting, currently running: ' . $processCount . PHP_EOL; pcntl_wait($status); $processCount--; continue; } echo 'Tasks running: ' . $processCount . PHP_EOL; $task = $taskList->current(); $taskList->next(); $processCount++; $pid = pcntl_fork(); if ($pid === -1) { exit('Error forking...' . PHP_EOL); } if ($pid === 0) { $processList[] = getmypid(); echo 'Running task as pid: ' . getmypid() . PHP_EOL; execute_task($task); exit(); } } while ($taskList->valid()); $waitForChildrenToFinish = true; while ($waitForChildrenToFinish) { // This while loop holds the parent process until all the child threads // are complete - at which point the script continues to execute. if (pcntl_waitpid(0, $status) === -1) { echo 'parallel execution is complete' . PHP_EOL; $waitForChildrenToFinish = false; } } // Code to run after all tasks are processed } launch(); ---- Server IP: 45.112.84.4 Probable Submitter: 80.90.5.135 (proxied: 2a01:e0a:88d:800:573c:b7ca:4440:3853) ---- Manual Page -- https://php.net/manual/en/function.pcntl-fork.php Edit -- https://main.php.net/note/edit/126991 Del: integrated -- https://main.php.net/note/delete/126991/integrated Del: useless -- https://main.php.net/note/delete/126991/useless Del: bad code -- https://main.php.net/note/delete/126991/bad+code Del: spam -- https://main.php.net/note/delete/126991/spam Del: non-english -- https://main.php.net/note/delete/126991/non-english Del: in docs -- https://main.php.net/note/delete/126991/in+docs Del: other reasons-- https://main.php.net/note/delete/126991 Reject -- https://main.php.net/note/reject/126991 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#218259) next »