: This article describes how to implement multiple threads in php. For more information about PHP tutorials, see. Use the Socket method of php to implement multithreading of php programs. Php itself does not support multithreading. how can we implement multithreading in php? The WEB server itself supports multiple threads. Every visitor accesses the WEB page and calls a new thread. through this, we can use the thread of the WEB server to solve the problem that PHP does not support multithreading.
The following is a PHP multi-threaded code that uses fsockopen () to establish a socket connection and then uses fputs () to send messages:
$ Fp = fsockopen ($ _ SERVER ['http _ host'], 80, & $ errno, & $ errstr, 5 );
If (! $ Fp ){
Echo "$ errstr ($ errno)
\ N ";
}
Fputs ($ fp, "GET $ _ SERVER [PHP_SELF]? Flag = 1 \ r \ n ");
Fclose ($ fp );
The above code is only a thread operation process. A few more such operations are multithreading. Currently, the so-called PHP multi-threaded program is based on this method.
The following is a complete thread-class code.
/**
@ Title: PHP multithreading class (Thread)
@ Version: 1.0
@ Author: axgle
*/
Class thread {
Var $ count;
Function thread ($ count = 1 ){
$ This-> count = $ count;
}
Function _ submit (){
For ($ I = 1; $ I <= $ this-> count; $ I ++) $ this-> _ thread ();
Return true;
}
Function _ thread (){
$ Fp = fsockopen ($ _ SERVER ['http _ host'], 80, & $ errno, & $ errstr, 5 );
If (! $ Fp ){
Echo "$ errstr ($ errno)
\ N ";
}
Fputs ($ fp, "GET $ _ SERVER [PHP_SELF]? Flag = 1 \ r \ n ");
Fclose ($ fp );
}
Function exec ($ func ){
Isset ($ _ GET ['flag'])? Call_user_func ($ func): $ this-> _ submit ();
}
}
// Application example:
$ Th = new thread (10); // 10 threads
$ Th-> exec ('demo'); // executes a row-defined function.
Function demo (){
Fopen ('data/'. microtime (), 'w ');
}
?>
Http://codechina.spaces.live.com/blog/cns! Bca6db10a924c24! 575. entry
The above introduces the implementation of multi-threading in php, including the content, hope to be helpful to friends who are interested in the PHP Tutorial.