Php itself is not ideal for multi-threaded processing, but if we use pthreads, the performance will be improved. Let's look at a PHP multi-threaded pthreads example. php itself is not ideal for multi-threaded processing, however, if we use pthreads, the performance will be improved. The following shows an example of PHP multithreading pthreads.
Script ec (2); script
Declare (ticks = 1 );
$ Running = 1;
// Signal Processing Function
Function sig_handler ($ signo)
{
Switch ($ signo ){
Case SIGINT:
Finish ();
Break;
Default:
Break;
}
}
Pcntl_signal (SIGINT, "sig_handler ");
Class test extends \ Thread {
Public $ url;
Public $ result;
Public function _ construct ($ url ){
$ This-> url = $ url;
}
Public function run (){
If ($ this-> url ){
$ This-> result = model_http_curl_get ($ this-> url );
}
}
}
Function model_http_curl_get ($ url ){
$ 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, 'mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2 )');
$ Result = curl_exec ($ curl );
Curl_close ($ curl );
Return $ result;
}
For ($ I = 0; I I <500; $ I ++ ){
$ Urls [] = 'HTTP: // www.baidu.com/s? Wd = '. rand (10000,200 00 );
}
$ Pool = array ();
For ($ I = 1; $ I <= 5; $ I ++ ){
$ Key = uniqid ();
$ Url = array_shift ($ urls );
$ Pool [$ key] = new test ($ url );
$ Pool [$ key]-> start ();
Echo "Starting thread $ key \ n ";
}
While ($ urls & $ running ){
Foreach ($ pool as $ key => $ worker ){
If (! $ Worker-> isRunning ()){
// Unset ($ pool [$ key]);
Echo "Thread". $ key. "ended \ n ";
$ Url = array_shift ($ urls );
$ Pool [$ key] = new test ($ url );
$ Pool [$ key]-> start ();
Echo "Starting thread $ key \ n ";
}
}
Usleep (1000 );
}
Function finish (){
Global $ running;
Global $ pool;
$ Running = 0;
Echo "Received Signal, waiting for running thread to end \ n ";
Foreach ($ pool as $ key => $ worker ){
If ($ pool [$ key]-> join ()){
Var_dump ($ pool [$ key]-> result );
}
}
}