PHP Multi-threaded implementation methods and usage examples, PHP multi-threaded instance detailed _php tutorial

Source: Internet
Author: User

PHP Multi-threaded implementation methods and usage examples, PHP multi-threaded instance of the detailed


Below we introduce the specific PHP multithreaded implementation program code, there is a need to understand the students can refer to.
When someone wants to implement concurrency, they usually think of using fork or spawn threads, but when they find out that PHP doesn't support multithreading, they probably switch ideas to use some of the language that's not good enough, like Perl.
In fact, in most cases, you don't have to use fork or thread, and you get better performance than fork or thread.
Suppose you want to set up a service to check the running N servers to make sure they're still working. You might write the following code:
The code is as follows

<?php$hosts = Array ("host1.sample.com", "host2.sample.com", "host3.sample.com"), $timeout = n; $status = array (); foreach ($hosts as $host) {$errno = 0; $errstr = ""; $s = Fsockopen ($host, $errno, $errstr, $timeout); if ($s) {$status [$host] = "Connectedn"; fwrite ($s, "head/http/1.0rnhost: $hostrnrn"); do {  $data = fread ($s, 8192);  if (strlen ($data) = = 0) {break  ;  }  

It works fine, but before Fsockopen () parses hostname and establishes a successful connection (or delay $timeout seconds), it takes a long time to expand the code to manage a large number of servers.
so we have to give up this code; We can establish an asynchronous connection-there is no need to wait for Fsockopen to return to the connection state. PHP still needs to parse hostname (so it's more sensible to use IP directly), but will return immediately after opening a connection, and then we can connect to the next server.
There are two ways to implement : PHP5 can replace the Fsocketopen () directly with the new Stream_socket_client () function. PHP5 the previous version, you need to do it yourself and use the sockets extension to solve the problem.
The following is the workaround in PHP5:
Code as follows

<?php$hosts = Array ("host1.sample.com", "host2.sample.com", "host3.sample.com"), $timeout = n; $status = array (); $ sockets = Array ();/* Initiate connections to all the hosts simultaneously */foreach ($hosts as $id = = $host) {$s = str Eam_socket_client ("$ $host: $", $errno, $errstr, $timeout, stream_client_async_connect| Stream_client_connect); if ($s) {$sockets [$id] = $s; $status [$id] = "in progress";} else {$status [$id] = "failed, $errno $errstr";}} /* Now, wait for the results-come back in */while (count ($sockets)) {$read = $write = $sockets;/* This is the Magic F unction-explained below */$n = Stream_select ($read, $write, $e = null, $timeout); if ($n > 0) {/* Readable sockets either has data for us, or is failed * Connection attempts */foreach ($read as $r   {$id = Array_search ($r, $sockets);   $data = Fread ($r, 8192);  if (strlen ($data) = = 0) {if ($status [$id] = = "in progress") {$status [$id] = ' failed to connect ';  } fclose ($r);   Unset ($sockets [$id]);} else {$status [$id]. = $data;  }}/* Writeable sockets can accept an HTTP request */foreach ($write as $w) {$id = Array_search ($w, $sockets); Fwrite ($w, "Head/http/1.0rnhost:".) $hosts [$id].  "Rnrn"); $status [$id] = "Waiting for response"; }} else {/* timed out waiting; Assume, all hosts associated * with $sockets is faulty */foreach ($sockets as $id = = $s) {$status [$id] = "Timed out". $status [$id]; } break; }}foreach ($hosts as $id = $host) {echo "host: $hostn"; echo "Status:". $status [$id]. "NN";}  ?>

We use Stream_select () to wait for sockets to open the connection event. Stream_select () calls the system's Select (2) function to work: The first three parameters are the array of streams you want to use, and you can read, write, and get exceptions (for three parameters, respectively). Stream_select () Can wait for an event to occur by setting the $timeout (seconds) parameter-the corresponding sockets data will be written to the parameter you passed in when the event occurs.
The following is the implementation of the version after PHP4.1.0 , if you have compiled PHP with sockets (ext/sockets) support, you can use the root above similar code, just need to put the above streams/ The function of the FileSystem function is implemented with the Ext/sockets function. The main difference is that we use the following function instead of stream_socket_client () to establish a connection:
The code is as follows

<?php//This value was correct for Linux, and other systems had the other valuesdefine (' einprogress ', (); function Non_blockin G_connect ($host, $port, & $errno, & $errstr, $timeout) {$ip = gethostbyname ($host); $s = Socket_create (af_inet, SOC K_stream, 0); if (Socket_set_nonblock ($s)) {$r = @socket_connect ($s, $ip, $port); if ($r | | socket_last_error () = = einprogress) {  $ errno = einprogress;  

Now replace Stream_select () with Socket_select (), replace fread () with Socket_read (), replace Socket_write () with fwrite (), Socket_close () Replace fclose () to execute the script!
PHP5 Advanced is that you can use the Stream_select () Handle almost all stream-for example, you can use the include stdin to receive keyboard input and save into an array, and you can also receive data from a pipeline opened by Proc_open ().
below to share a PHP multithreaded class
code as follows

* @title: PHP multithreaded Class (thread) * @version: 1.0 * * PHP Multithreaded Application Example: * require_once ' thread.class.php '; * $thread = new Thread (); * $thread->addthread (' Action_log ', ' a '); * $thread->addthread (' Action_log ', ' B '); * $thread->addthread (' Action_log ', ' C '); * $thread->runthread (); * * Function Action_log ($info) {* $log = ' log/'. Microtime (). '. log '; * $txt = $info. "Rnrn". ' Set in '. Date (' H:i:s ', Time ()). (double) microtime (). "RN"; * $fp = fopen ($log, ' w '); * Fwrite ($FP, $txt); * Fclose ($FP);  *} */class Thread {var $hooks = array ();   var $args = array ();    function thread () {} function Addthread ($func) {$args = Array_slice (Func_get_args (), 1);    $this->hooks[] = $func;    $this->args[] = $args;  return true;    } function Runthread () {if (Isset ($_get[' flag ')) {$flag = intval ($_get[' flag ']);    if ($flag | | $flag = = = 0) {call_user_func_array ($this->hooks[$flag], $this->args[$flag]); } else {for ($i = 0, $size = count ($this->hooks); $i < $size;        $i + +) {$fp =fsockopen ($_server[' http_host '],$_server[' server_port ']);          if ($fp) {$out = "GET {$_server[' php_self ']}?flag= $i http/1.1rn";          $out. = "Host: {$_server[' http_host ']}rn";          $out. = "Connection:closernrn";          Fputs ($fp, $out);        Fclose ($FP); }      }    }  }}

I hope this article is helpful to everyone's PHP programming.

http://www.bkjia.com/PHPjc/1065154.html www.bkjia.com true http://www.bkjia.com/PHPjc/1065154.html techarticle PHP Multi-threaded implementation methods and usage examples, PHP multi-threaded examples below we introduce the specific PHP multithreaded implementation program code, there is a need to understand the students can refer to. When someone wants to ...

  • 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.