Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- $procs = 4;
- $iterations = 10;
- $pids = array();
- $iproc = -1;
- function my_launch($i, $proc) {
- echo "Process $proc ran iteration $i.\n";
- }
- $pid = 0;
- for ($i = 0; $i < $procs; $i++) {
- $pid = pcntl_fork();
- if ($pid > 0) {
- // I am the parent process
- $pids[$pid] = $pid;
- } elseif ($pid == -1) {
- //error occurred, use available processes only
- $nproc = $i;
- break;
- } else {
- //I am the child process.
- $iproc = $i;
- break;
- }
- }
- $nproc = !empty($nproc) ? $nproc : $procs;
- if ($nproc == 0) {
- echo "NOTICE: Process could not be forked; proceeding in serial.\n";
- for ($i = 0; $i < $iterations; $i++) {
- my_launch($i, $iproc);
- }
- exit;
- }
- if ($nproc != $procs) {
- echo "NOTICE: Only using $nprocs processes out of the hoped $procs.\n";
- }
- $iterationsPerProcess = (int) ($iterations / $nproc);
- // children do the main work.
- if ($pid == 0) {
- $stopAt = $iterationsPerProcess * ($iproc + 1);
- for ($i = ($iproc * $iterationsPerProcess); $i < $stopAt; $i++) {
- my_launch($i, $iproc);
- }
- }
- if ($pid > 0) {
- // parent process picks up the remainder of the work
- $i = $nproc * ((int) ($iterations / $nproc));
- for (; $i < $iterations; $i++) {
- my_launch($i, "Main");
- }
- //wait for children to finish
- $status = -1;
- foreach ($pids as $createdIndex => $pid) {
- pcntl_waitpid($pid, $status);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment