Skillfully solve the problem that PHP cannot implement multithreading

Source: Internet
Author: User
Tags foreach array fread http request implement include connect strlen

Is there a 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? 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 might write the following code:

  1. 		$hosts = Array ("host1.sample.com", "host2.sample.com", "host3.sample.com");
  2. $timeout = 15;
  3. $status = Array ();
  4. foreach ($hosts as $host) {
  5. $errno = 0;
  6. $errstr = "";
  7. $s = Fsockopen ($host, $errno, $errstr, $timeout);
  8. if ($s) {
  9. $status [$host] = "Connectedn";
  10. Fwrite ($s, "head/http/1.0rnhost: $hostrnrn");
  11. do {
  12. $data = Fread ($s, 8192);
  13. if (strlen ($data) = = 0) {
  14. Break
  15. }
  16. $status [$host]. = $data;
  17. }
  18. while (true);
  19. Fclose ($s);
  20. }
  21. else {
  22. $status [$host] = "Connection failed: $errno $errstrn";
  23. }
  24. }
  25. Print_r ($status);
  26. ?>

It works well, but it can take a long time to extend this code to manage a large number of servers before Fsockopen () finishes analyzing hostname and building 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 to the connection state. 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:

  1. 		$hosts = Array ("host1.sample.com", "host2.sample.com", "host3.sample.com");
  2. $timeout = 15;
  3. $status = Array ();
  4. $sockets = Array ();
  5. /* Initiate connections to all the hosts simultaneously * *
  6. foreach ($hosts as $id => $host) {
  7. $s = Stream_socket_client ("$host:), $errno, $errstr, $timeout,
  8. Stream_client_async_connectstream_client_connect);
  9. if ($s) {
  10. $sockets [$id] = $s;
  11. $status [$id] = "in progress";
  12. }
  13. else {$status [$id] = "failed, $errno $errstr";
  14. }
  15. }
  16. * Now, wait for the "results to" come back in * *
  17. while (count ($sockets)) {
  18. $read = $write = $sockets;
  19. /* This is the magic function-explained below * *
  20. $n = Stream_select ($read, $write, $e = null, $timeout);
  21. if ($n > 0) {
  22. /* Readable sockets either have data for us, or are failed * Connection attempts * *
  23. foreach ($read as $r) {
  24. $id = Array_search ($r, $sockets);
  25. $data = Fread ($r, 8192);
  26. if (strlen ($data) = = 0) {
  27. if ($status [$id] = = "in progress") {
  28. $status [$id] = "failed to connect";
  29. }
  30. Fclose ($R);
  31. Unset ($sockets [$id]);
  32. }
  33. else {
  34. $status [$id]. = $data;
  35. }
  36. }
  37. /* Writeable sockets can accept an HTTP request * * *
  38. foreach ($write as $w) {
  39. $id = Array_search ($w, $sockets);
  40. Fwrite ($w, "Head/http/1.0rnhost:"
  41. .  $hosts [$id]. "Rnrn");
  42. $status [$id] = "Waiting for response";
  43. }
  44. }
  45. else {
  46. /* timed out waiting; Assume, all hosts associated * with $sockets are faulty * *
  47. foreach ($sockets as $id => $s) {
  48. $status [$id] = "Timed out"
  49. . $status [$id];
  50. }
  51. Break
  52. }
  53. }
  54. foreach ($hosts as $id => $host) {
  55. echo "Host: $hostn"; echo "Status:"
  56. . $status [$id]. "NN";
  57. }
  58. ?>

We use Stream_select () to wait for the sockets open 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; 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 establish the connection:

  1. 		This value is correct for Linux, and other systems have other values
  2. Define (' einprogress ', 115);
  3. function Non_blocking_connect ($host, $port, & $errno, & $errstr, $timeout) {
  4. $ip = gethostbyname ($host);
  5. $s = socket_create (af_inet, sock_stream, 0);
  6. if (Socket_set_nonblock ($s)) {
  7. $r = @socket_connect ($s, $ip, $port);
  8. if ($r socket_last_error () = = einprogress) {
  9. $errno = einprogress;
  10. return $s;
  11. }
  12. }
  13. $errno = Socket_last_error ($s);
  14. $errstr = Socket_strerror ($errno);
  15. Socket_close ($s);
  16. return false;
  17. }
  18. ?>

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! The PHP5 is that you can use Stream_select () to handle almost any 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 pipe opened through Proc_open ().



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.