PHP Implementation Multithreading

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.