Data is independent in multiple processes, variables cannot be shared, so you can use SHMOP Shared memory implementations (CLI mode does not support APC extensions), or it is stored in a nosql such as Redis.
The following example, open 10 processes combined with Redis collection, do some simple task processing.
1<?PHP2 for($i= 0;$i<10;$i++){//Open 10 Processes3 $ret= Pcntl_fork ();//Build Process4 5 if($ret= = 0){6 7 $redis=NewRedis ();8 $redis->connect (' 127.0.0.1 ', 6379);9 Ten while(true){//Make a loop and let the process run again and again One A if($redis->setnx (' job ', 1) ==1) {//Locking - - if(Count($redis->keys (' webpub ')) = = 0) {//no data in the collection goes out of the loop the $redis->del (' job ');//Unlock - Continue; - } - + $getjob=$redis->zrange (' Webpub ', 0,0);//Take out a - Var_dump($getjob); + //Open Transaction A $redis-multi (); at - //ordered collection Delete - $redis->zrem (' Webpub ',$getjob[0]);//Delete - $redis->del (' job ');//Unlock - - //Execute transaction code in $redis-exec(); - to //the following represent the tasks to be performed + file_put_contents('./job/').$getjob[0]. '. HTML ',$getjob[0]); - the Echo $getjob[0]. ' is do '.Php_eol; * $ Sleep(1);Panax Notoginseng } - } the } +}
The above code opens 10 processes to handle the tasks in the Webpub collection in Redis, where the task is relatively simple to generate a file. It is important to note that in order to prevent a task from being processed concurrently between multiple processes, a lock must be added to limit it.
PS: Do not know the above code whether there is a pit, like me wild yards involved in a bit of deep things may appear a variety of pits.
PHP Multi-process Pcntl Learning (ii)