PHP through the socket way to implement the multi-threaded PHP program. PHP itself does not support multi-threaded, then how to implement multithreading in PHP? As you can imagine, the Web server itself is multi-threaded. Every visitor, when accessing a Web page, calls a new thread, which we can take advantage of the Web server's own thread to solve the problem that PHP does not support multithreading.
The following is a PHP multithreaded class code that is implemented by establishing a socket connection via Fsockopen () and then sending a message with fputs ():
$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 just a thread of the operation process. A few more of these operations are multithreaded. Currently, the so-called PHP multi-threaded program is based on this way.
The following gives a complete thread class code.
<?php
/**
@title:P hp multithreaded Class (thread)
@version: 1.0
@author: Axgle <[email protected]>
*/
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 Examples:
$th =new Thread (10);//10 Threads
$th->exec (' demo ');//Perform line-custom functions
Function Demo () {
fopen (' data/'. Microtime (), ' W ');
}
?>
Http://codechina.spaces.live.com/blog/cns!bca6db10a924c24!575.entry
PHP Implementation Multithreading