php implements multithreading

WBOY
Release: 2016-08-08 09:32:49
Original
911 people have browsed it

Realize multi-threading of PHP programs 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 class code that establishes a socket connection through fsockopen() 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=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-thread 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

The above introduces the implementation of multi-threading in PHP, including aspects of it. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
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