note 37039 deleted from function.pcntl-fork by nlopess

From: Date: Sat, 22 Jul 2006 11:38:53 +0000
Subject: note 37039 deleted from function.pcntl-fork by nlopess
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-115042@lists.php.net to get a copy of this message
Note Submitter: Jazeps Basko, jb4 [at] 42901.lv ---- Here is my example how one can create a number of threads that do the same thing. The thing that each instance should execute is written in Process::go() method. This code creates three threads called a, b and c. They all do the same thing: they iterate ten times through a loop that says them to wait for a second and then print out their name and the iteration number. If you executed this on your UNIX machine that has PHP installed in /usr/local/phpcli (change that if you have PHP elsewhere), you'd get smth like this: a1 b1 c1 a2 b2 c2 a3 ... .. a9 b9 c9 [ note that the order how a1, b1, c1 appear may change - if by some reason a thread goes a little bit slower than b or c, it would appear after the b1 and c1, and other iteration indicators of b, c threads too ] So, here comes the code: #! /usr/local/phpcli/bin/php -q <?php /* PHP jaabuut kaa CGI, --enable-pcntl */ class Process { var $ident; function Process( $ident ) { $this->ident = $ident; } function go() { for ( $i=1; $i<10; $i++ ) { sleep(1); echo $this->ident . $i . "\n"; } } } $childrenTotal = 3; $childrenNow = 0; $childrenNames = array( 'a', 'b', 'c' ); while ( $childrenNow < $childrenTotal ) { $pid = pcntl_fork(); if ( $pid == -1 ) { die( "error\n" ); } elseif ( $pid == 0 ) { $childrenNow++; } else { $process = new Process( $childrenNames[$childrenNow] ); $process->go(); die(); } } ?>

« previous php.notes (#115042) next »