Guest User

PHP PCNTL example

a guest
Nov 7th, 2012
42
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.49 KB | None | 0 0
  1. <?php
  2.  
  3. $procs = 4;
  4. $iterations = 10;
  5. $pids = array();
  6.  
  7. $iproc = -1;
  8.  
  9. function my_launch($i, $proc) {
  10.     echo "Process $proc ran iteration $i.\n";
  11. }
  12.  
  13. $pid = 0;
  14. for ($i = 0; $i < $procs; $i++) {
  15.     $pid = pcntl_fork();
  16.     if ($pid > 0) {
  17.         // I am the parent process
  18.         $pids[$pid] = $pid;
  19.  
  20.     } elseif ($pid == -1) {
  21.         //error occurred, use available processes only
  22.         $nproc = $i;
  23.         break;
  24.  
  25.     } else {
  26.         //I am the child process.
  27.         $iproc = $i;
  28.         break;
  29.     }
  30. }
  31.  
  32. $nproc = !empty($nproc) ? $nproc : $procs;
  33.  
  34. if ($nproc == 0) {
  35.     echo "NOTICE: Process could not be forked; proceeding in serial.\n";
  36.     for ($i = 0; $i < $iterations; $i++) {
  37.         my_launch($i, $iproc);
  38.     }
  39.     exit;
  40. }
  41.  
  42. if ($nproc != $procs) {
  43.     echo "NOTICE: Only using $nprocs processes out of the hoped $procs.\n";
  44. }
  45.  
  46. $iterationsPerProcess = (int) ($iterations / $nproc);
  47.  
  48. // children do the main work.
  49. if ($pid == 0) {
  50.     $stopAt = $iterationsPerProcess * ($iproc + 1);
  51.  
  52.     for ($i = ($iproc * $iterationsPerProcess); $i < $stopAt; $i++) {
  53.         my_launch($i, $iproc);
  54.     }
  55. }
  56.  
  57. if ($pid > 0) {
  58.     // parent process picks up the remainder of the work
  59.     $i = $nproc * ((int) ($iterations / $nproc));
  60.     for (; $i < $iterations; $i++) {
  61.         my_launch($i, "Main");
  62.     }
  63.  
  64.     //wait for children to finish
  65.     $status = -1;
  66.     foreach ($pids as $createdIndex => $pid) {
  67.         pcntl_waitpid($pid, $status);
  68.     }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment