realizes multi-threading of php program through php's Socket method. PHP itself does not support multi-threading, so how to implement multi-threading in PHP? You can think about it, the WEB server itself supports multi-threading. Each visitor will call a new thread when accessing the WEB page. Through this, we can use the WEB server's own thread to solve the problem that PHP does not support multi-threading.
The following is a PHP multi-threaded code that establishes a socket connection through fsockopen() and then sends a message using fputs():
$fp=fsockopen($_SERVER['HTTP_HOST'] ,80,&$errno,&$errstr,5);
if(!$fp){
echo "$errstr ($errno)
n";
}
fputs($fp,"GET $_SERVER[PHP_SELF]?flag=1rn");
fclose($fp);
The above code is just a thread operation process. Performing a few more such operations is multi-threading. The current so-called multi-threaded programs of PHP are all based on this method.
A complete thread class code is given below.
/**
@title:PHP Multi-Threading 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=1rn");
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');//Execute a custom function
function demo() {
fopen('data/'.microtime(),'w');
}
?>
http://codechina.spaces.live.com/blog/cns!bca6db10a924c24!575.entry