PHP implements multi-threading, PHP multi-threading_PHP tutorial

WBOY
Release: 2016-07-13 10:12:00
Original
925 people have browsed it

php realizes multi-threading, php multi-threading

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

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/924848.htmlTechArticlephp implements multi-threading. PHP multi-threading implements multi-threading of PHP programs through the Socket method of PHP. PHP itself does not support multi-threading, so how to implement multi-threading in PHP? You can think about it...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!