PHP Implementation Multithreading

Source: Internet
Author: User
Tags foreach fread strlen

  Is there any way to implement multithreading in PHP? Suppose you are writing a PHP application based on multiple servers, ideally sending requests to multiple servers at the same time instead of one after the other. Can it be achieved? The answer is certainly yes, look at the solution  

Answer: 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 language that isn't good enough, like Perl. In fact, in most cases, you don't have to use fork or threads, and you get better performance than using 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 may write the following code:     Code as follows: <?php  $hosts = Array ("host1.sample.com", "host2.sample.com", " Host3.sample.com ");  $timeout = 15; $status = Array ();  foreach ($hosts as $host) {  $errno = 0;  $errstr = "";  $s = fsockopen ($host, 80, $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;} $status [$host]. = $data; nbsp } while (true); Fclose ($s); } else {  $status [$host] = "Connection failed: $errno $errstrn",; } }  print_r ($sta TUS); ?>     It works well, but it will take a long time to extend this code to manage a large number of servers before Fsockopen () analyzes hostname and establishes a successful connection (or delay $timeout seconds). So we have to discard this code; We can establish an asynchronous connection-no need to wait for Fsockopen to return the connectionState. PHP still needs to parse hostname (so it's more sensible to use IP directly), but it will return immediately after opening a connection, and then we can connect to the next server. There are two ways to implement this; PHP5 can replace Fsocketopen () directly with the new Stream_socket_client () function. Before the PHP5 version, you need to do it yourself and use the sockets extension to solve the problem. Here is the workaround in PHP5: The   code is as follows: <?php  $hosts = Array ("host1.sample.com", "host2.sample.com", "host3.sample.com");   $timeout = 15;  $status = Array ();  $sockets = Array ();  foreach ($hosts as $id => $host) {  $s = Stream_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"; } }  while (count ($sockets)) {  $read = $write = $sockets;   $n = Stream_select ($read, $write, $e = null, $timeout);  if ($n > 0) {  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; } }  foreach ($write as $w) {  $id = Array_search ($w, $sockets);  Fwrit E ($w, "Head/http/1.0rnhost:". $hosts [$id]. "Rnrn");  $status [$id] = "Waiting for response"; } } else {  foreach ($sockets as $id => $s) {&NB Sp $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 connection events. Stream_select () calls the system's Select (2) function to work: The first three parameters are the array of streams you want to use; You can read, write, and get exceptions (three parameters, respectively). Stream_select () Can wait for an event to occur by setting the $timeout (seconds) parameter, and the corresponding sockets data will be written to the parameters you pass in. The following is the implementation of the PHP4.1.0 version, if you already include sockets (Ext/sockets) support in compiling PHP, you can use code similar to the root, just need to use the function of the above Streams/filesystem function ext/ sockets function implementation. The main difference is that we use the following function instead of   stream_socket_client () to buildVertical connection:   Code as follows: <?php //This value is correct for Linux, and other systems have values  define (' Einprog RESS ',;  function Non_blocking_connect ($host, $port, & $errno, & $errstr, $timeout) {  $ip = GetHost ByName ($host);  $s = socket_create (af_inet, sock_stream, 0);  if (Socket_set_nonblock ($s)) {  $r = @socket _connect ($s, $ip, $port);  if ($r | | | socket_last_error () = = einprogress) {  $errno = einprogress; return $s; &nbs P } }  $errno = Socket_last_error ($s);  $errstr = Socket_strerror ($errno);  socket_close ($s);  return false; } ?>     now replace Stream_select () with Socket_select (), replace Socket_read () with Fread (), and use   Socket_write () replaces fwrite () and replaces fclose () with Socket_close () to execute the script! The PHP5 is that you can use Stream_select () to handle almost any stream-for example, you can use it to receive keyboard input and save into an array via include  stdin, and you can also receive it via Proc_open () The data in the open pipe. If you want php4.3.x to have the ability to handle streams, I have a patch for you to get fsockopen to work asynchronously. Not in favor of using this patch, the patch will not appear in the officially released PHP version, I'm in the patchComes with the implementation of the Stream_socket_client () function, through which you can make your scripts compatible   PHP5.

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.