The implementation of php multi-process depends on the pcntl extension. During PHP compilation, you can add '-enable-pcntl' or compile it separately.
Note the following three points:
1. The sub-process does not execute the code before fork, but just copies the memory status of the parent process to a new one. Therefore, the personalized settings of the sub-process must be set separately.
2. Output redirection. Using echo in a program may cause command line confusion and affect resolution. You can use ob_start to redirect to the log file. Of course, it is better to use log directly. The log files in this instance are grouped by the process pid.
3. If no code is executed for the parent process, the child process may exit early and become an orphan process.
Demo acceptance:
Use 10 sub-processes to process output tasks. The total number of tasks is 1000. Then, the tasks are evenly distributed to 10 sub-processes.
| The code is as follows: |
Copy code |
|
<? Php
// Redirect the output to the log file
Function echo_to_log ($ content ){
Global $ current_pid;
$ Logfile = _ FILE _. $ current_pid. '. Log ';
$ Fp = fopen ($ logfile, 'A + ');
Fwrite ($ fp, $ content );
Fclose ($ fp );
}
Ob_start ('echo _ to_log ');
// Obtain the pid of the current process
$ Current_pid = getmypid ();
$ Fork_nums = 10;
$ Total = 1000;
For ($ I = 0; $ I <$ fork_nums; $ I ++ ){
$ Pid = pcntl_fork ();
// When it is equal to 0, it is a sub-process
If ($ pid = 0 ){
$ Current_pid = $ pid;
Do_task ($ I );
// If the value is greater than 0, it is the parent process and the pid is the PID of the child process generated
} Else if ($ pid> 0 ){
}
}
// Task functions
Function do_task ($ task_num ){
Global $ total;
$ Start = $ total/10 * $ task_num;
$ End = $ total/10 * ($ task_num + 1 );
For (; $ start <$ end; $ start ++ ){
Echo $ task_num. "". $ start. "\ n ";
}
// Terminate a sub-process after the task is executed. Of course, you can return the code of the main process for related operations.
Exit ();
} |
Multi-process control framework code for future reference
| The code is as follows: |
Copy code |
|
Declare (ticks = 1 );
Function sigHandler ($ signal)
{
Echo "a child exited \ n ";
}
Pcntl_signal (SIGCHLD, sigHandler, false );
Echo "this is". posix_getpid (). PHP_EOL;
For ($ I = 0; $ I <3; $ I ++)
{
$ Pid = pcntl_fork ();
If ($ pid =-1)
{
Echo 'fork failed'. PHP_EOL;
}
Else if ($ pid)
{
}
Else
{
$ Pid = posix_getpid ();
Echo 'child '. $ pid. ''. time (). PHP_EOL;
Sleep (rand (2, 5 ));
Echo 'child '. $ pid. 'Done'. time (). PHP_EOL;
Exit (0 );
}
}
Do
{
$ Pid = pcntl_wait ($ status );
Echo 'child quit'. $ pid. PHP_EOL;
} While ($ pid> 0 );
Echo 'parent done'. PHP_EOL; |
Example
A php multi-thread and For loop is provided to capture the PHP code example on the Baidu search page:
| The code is as follows: |
Copy code |
|
<? Php
Class test_thread_run extends Thread
{
Public $ url;
Public $ data;
Public function _ construct ($ url)
{
$ This-> url = $ url;
}
Public function run ()
{
If ($ url = $ this-> url ))
{
$ This-> data = model_http_curl_get ($ url );
}
}
}
Function model_thread_result_get ($ urls_array)
{
Foreach ($ urls_array as $ key => $ value)
{
$ Thread_array [$ key] = new test_thread_run ($ value ["url"]);
$ Thread_array [$ key]-> start ();
}
Foreach ($ thread_array as $ thread_array_key => $ thread_array_value)
{
While ($ thread_array [$ thread_array_key]-> isRunning ())
{
Usleep (10 );
}
If ($ thread_array [$ thread_array_key]-> join ())
{
$ Variable_data [$ thread_array_key] = $ thread_array [$ thread_array_key]-> data;
}
}
Return $ variable_data;
}
Function model_http_curl_get ($ url, $ userAgent = "")
{
$ UserAgent = $ userAgent? $ UserAgent: 'mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2 )';
$ Curl = curl_init ();
Curl_setopt ($ curl, CURLOPT_URL, $ url );
Curl_setopt ($ curl, CURLOPT_RETURNTRANSFER, 1 );
Curl_setopt ($ curl, CURLOPT_TIMEOUT, 5 );
Curl_setopt ($ curl, CURLOPT_USERAGENT, $ userAgent );
$ Result = curl_exec ($ curl );
Curl_close ($ curl );
Return $ result;
}
For ($ I = 0; I I <100; $ I ++)
{
$ Urls_array [] = array ("name" => "baidu", "url" => "http://www.baidu.com/s? Wd = ". mt_rand (Random, 20000 ));
}
$ T = microtime (true );
$ Result = model_thread_result_get ($ urls_array );
$ E = microtime (true );
Echo "multithreading:". ($ e-$ t). "\ n ";
$ T = microtime (true );
Foreach ($ urls_array as $ key => $ value)
{
$ Result_new [$ key] = model_http_curl_get ($ value ["url"]);
}
$ E = microtime (true );
Echo "For loop:". ($ e-$ t). "\ n ";
?> |
PHP multithreading)
| The code is as follows: |
Copy code |
/**
* @ Title: PHP multithreading class (Thread)
* @ Version: 1.0
* @ Author: <web @>
* @ Published: 2010-11-2
*
* PHP multithreading application example:
* Require_once 'thread. class. Php ';
* $ Thread = new thread ();
* $ Thread-> addthread ('Action _ log', 'A ');
* $ Thread-> addthread ('Action _ log', 'B ');
* $ Thread-> addthread ('Action _ log', 'C ');
* $ Thread-> runthread ();
*
* Function action_log ($ info ){
* $ Log = 'Log/'. microtime ().'. Log ';
* $ Txt = $ info. "rnrn ". 'set in '. date ('H: I: S', time ()). (double) microtime (). "rn ";
* $ Fp = fopen ($ log, 'w ');
* Fwrite ($ fp, $ txt );
* Fclose ($ fp );
*}
*/
Class thread {
Var $ hooks = array ();
Var $ args = array ();
Function thread (){
}
Function addthread ($ func)
{
$ Args = array_slice (func_get_args (), 1 );
$ This-> hooks [] = $ func;
$ This-> args [] = $ args;
Return true;
}
Function runthread ()
{
If (isset ($ _ GET ['flag'])
{
$ Flag = intval ($ _ GET ['flag']);
}
If ($ flag | $ flag = 0)
{
Call_user_func_array ($ this-> hooks [$ flag], $ this-> args [$ flag]);
}
Else
{
For ($ I = 0, $ size = count ($ this-> hooks); $ I <$ size; $ I ++)
{
$ Fp = fsockopen ($ _ SERVER ['http _ host'], $ _ SERVER ['server _ port']);
If ($ fp)
{
$ Out = "GET {$ _ SERVER ['php _ SELF ']}? Flag = $ I HTTP/1.1rn ";
$ Out. = "Host: {$ _ SERVER ['http _ host']} rn ";
$ Out. = "Connection: Closernrn ";
Fputs ($ fp, $ out );
Fclose ($ fp );
}
}
}
}
}
|
Usage:
| The code is as follows: |
Copy code |
|
$ Thread = new thread ();
$ Thread-> addthread ('function1', 'info1 ');
$ Thread-> addthread ('func2', 'info2 ');
$ Thread-> addthread ('func3', 'info3 ');
$ Thread-> runthread (); |
Note:
Addthread is used to add a thread function. The first parameter is the function name, and the subsequent parameter (optional) is the parameter passed to the specified function.
Runthread is the function of the execution thread.
In linux, you need to configure and install pthreads.
1. Extended compilation and installation (Linux), www.111cn.net edit parameter -- enable-maintainer-zts is required:
| The code is as follows: |
Copy code |
|
Php-5.5.1/cd/Data/tgz/
. /Configure -- prefix =/Data/apps/php -- with-config-file-path =/Data/apps/php/etc -- with-mysql =/Data/apps/mysql -- with-mysqli =/Data/apps/mysql/bin/mysql_config -- with-iconv-dir -- with-freetype-dir =/Data/apps/libs -- with-jpeg-dir = /Data/apps/libs -- with-png-dir =/Data/apps/libs -- with-zlib -- with-libxml-dir =/usr -- enable-xml -- disable-rpath -- enable-bcmath -- enable-shmop -- enable-sysvsem -- enable-inline-optimization -- with-curl -- enable-mbregex -- enable-fpm -- enable-mbstring -- with-mcrypt =/ data/apps/libs -- with-gd -- enable-gd-native-ttf -- with-openssl -- with-mhash -- enable-pcntl -- enable-sockets -- with-xmlrpc -- enable- zip -- enable-soap -- enable-opcache -- with-pdo-mysql -- enable-maintainer-zts
Make clean
Make
Make install
Unzip pthreads-master.zip
Cd pthreads-master
/Data/apps/php/bin/phpize
./Configure -- with-php-config =/Data/apps/php/bin/php-config
Make
Make install
Vi/Data/apps/php/etc/php. ini
|
Add:
| The code is as follows: |
Copy code |
| Extension = "pthreads. so" |
PHP extensions: https://github.com/krakjoe/pthreads
PHP Manual: http://php.net/manual/zh/book.pthreads.php