note 37039 added to function.pcntl-fork

From: Date: Fri, 31 Oct 2003 13:01:16 +0000
Subject: note 37039 added to function.pcntl-fork
Groups: php.notes 
Request: Send a blank email to php-notes+get-59574@lists.php.net to get a copy of this message
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(); } } ?> ---- Manual Page -- http://www.php.net/manual/en/function.pcntl-fork.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+37039 Delete -- http://master.php.net/manage/user-notes.php?action=delete+37039&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+37039&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#59574) next »