Multithreading in php and multithreading in php
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) <br/> \ 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.
<? Php
/**
@ Title: PHP multithreading class (Thread)
@ Version: 1.0
@ Author: axgle <axgle@126.com>
*/
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) <br/> \ 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