PHP multi-process processing parallel Processing Task instance

Source: Internet
Author: User

Purpose of this article

In this paper, we explain the Linux environment using PHP for concurrent task processing and how to use pipe to synchronize data between processes. It's easy to write, as a memo.

PHP Multi-process

Use the multi-process functionality with the PCNTL_XXX series functions. Note: Pcntl_xxx can only run in the PHP CLI (command line) environment, in the Web server environment, there will be unexpected results, please use it with caution!

Piping pipe

Pipelines are used to host communication data between abbreviations. To facilitate understanding, the pipeline can be likened to a file, process a writes the data to the pipe p, and then process B reads the data from the pipe p. PHP provides the same pipeline operations API as the API for manipulating files, except that the POSIX_MKFIFO function is used to create pipelines, and reads and writes are the same as file manipulation functions. Of course, you can use the file to simulate the pipeline directly, but you can't use the features of the pipeline.

Zombie Process

At the end of the child process, the parent process does not wait for it (by calling wait or Waitpid), and the child process does not release all resources after the end (wasted!). ), this process is called the zombie process, he stored the child process at the end of the relevant data, if the zombie process too much, will occupy a lot of system resources (such as memory), affecting the performance of the machine.

Code

Nonsense less say directly on the code

/** * This was a demo for PHP fork and pipe usage. Fork Use * To create child process and pipe is used to sychoroize * th E child process and its main process. * @author Bourneli * @date: 2012-7-6*/ Define("PC", 10);//Number of processesDefine("to", 4);//timed outDefine("TS", 4);//event span, for simulating task delay if(!function_exists(' Pcntl_fork ')) {     die("Pcntl_fork Not existing");} //Creating Pipelines$sPipePath= "My_pipe."posix_getpid ();if(!posix_mkfifo ($sPipePath, 0666)) {     die("Create pipe {$sPipePath} error ");} //Simulating task concurrency for($i= 0;$i< PC; ++$i ) {    $nPID= Pcntl_fork ();//Create Child process    if($nPID= = 0) {        //Child process Process        Sleep(Rand(1,ts));//Analog Delay        $oW=fopen($sPipePath, ' W '); fwrite($oW,$i." \ n ");//The current task finishes processing, and the data is written in the pipeline        fclose($oW); Exit(0);//exit after execution    }} //Parent Process$oR=fopen($sPipePath, ' R ');stream_set_blocking($oR,FALSE);//set the pipeline to non-clogging to accommodate the timeout mechanism$sData= ";//storing data in a pipeline$nLine= 0;$nStart= Time(); while($nLine< PC && ( Time() -$nStart) <To ) {    $sLine=fread($oR, 1024); if(Empty($sLine)) {        Continue; }           Echo"Current line: {$sLine}\n "; //used to analyze how many tasks have been processed and identified by ' \ n '    foreach(Str_split($sLine) as $c) {        if("\ n" = =$c) {            ++$nLine; }    }    $sData.=$sLine;}Echo"Final Line count:$nLine\ n ";fclose($oR);unlink($sPipePath);//Delete the pipeline, it has no effect//wait for the child process to complete, avoid the zombie process$n= 0; while($n<PC) {    $nStatus=-1; $nPID= Pcntl_wait ($nStatus,Wnohang); if($nPID> 0) {        Echo"{$nPID} exit\n "; ++$n; }} //verify the results to see if each task is completed in the results$arr 2=Array();foreach(Explode("\ n",$sData) as $i) {//Trim All    if(Is_numeric(Trim($i))) {        Array_push($arr 2,$i); }}$arr 2=Array_unique($arr 2);if(Count($arr 2) ==PC) {     Echo' OK ';} Else {    Echo"Error Count".Count($arr 2) . "\ n"; Var_dump($arr 2);}

Reprinted address: Http://www.cnblogs.com/bourneli/archive/2012/07/06/2579893.htm

PHP multi-process processing parallel Processing Task instance

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.