PHP Implementation method of asynchronous call multithreading

Source: Internet
Author: User
Tags php multithreading mail account
In the previous article we give you a description of PHP multi-threading implementation, so today we give you a detailed introduction of PHP implementation of asynchronous multi-threaded method, I hope that this article to let you know more about PHP multi-threading further advanced!

For example, there is a scene, to send 1000 users a referral mail, the user input or import mail account to submit the server to perform the send

The first solution:

<?php$count=count ($emailarr); for ($i =0; $i < $count; $i) {sendmail (...); /Send mail}?>

This Code user experience is very poor, and can not actually use, the first to send so many messages will result in server run time-out, in fact, long user wait time will let users doubt and loss of confidence in the system products. However, the user does not have to wait until 1000 messages have been sent complete before the submission is successful, we can submit the background directly to the user prompt to send the success, and then let the background program silently sent.

Second workaround:


We try to execute the code using asynchronous execution, which is characterized by a background quiet execution, which the user does not have to wait for the result of the code execution, using the benefits of asynchronous execution:

1. Get rid of the application's dependency on a single task

2. Improved execution efficiency of the program

3. Improve the extensibility of the program

4. Improved user experience in a certain scenario

5. Because PHP does not support multi-threading, the use of asynchronous calls to request more than one HTTP way to achieve the program parallel execution effect, but note that the request of excessive HTTP, will greatly increase the system overhead

User experience: User waits, Send complete
Then send the task to a separate processing of the sending of the PHP program processing, when the user saw "send complete" when the fact that the letter has not been sent, this time, the sending program is working in the background, a lunar of the outgoing

<?php $domain = "www.***.com"; $url = "/system_mail.php"; $par = "email=". Implode (', ', $emailarr). " &, ... "; $header = "POST $url http/1.0rn"; $header. = "CONTENT-TYPE:APPLICATION/X-WWW-FORM-URLENCODEDRN"; $header. = "Content-length:". Strlen ($par). "Rnrn"; $fp = @fsockopen ($domain, $errno, $errstr, 30); Fputs ($FP, $header. $par); Fclose ($FP); Echo ' send complete ';?> system_mail.php <?php ini_set ("Ignore_user_abort", true); Ignore_user_abort (TRUE);//The code here needs to php.ini open the relevant options, to ensure that PHP execution does not time out, do not understand, refer to my other article, "Close the browser, PHP script will not continue to run"//get an email address, send letters, Here is the sending code?>

The third method:

1. The simplest approach is to embed an AJAX call in the HTML code returned to the client, or embed an IMG tag, which points to the time-consuming script to execute.
This method is the simplest and fastest. The server side does not have to make any calls.
However, the disadvantage is that, in general, Ajax should be triggered after the onload, that is, the user points to open the page, then close, it will not trigger our background script.
In the case of an IMG tag, this approach cannot be called a strict asynchronous execution. The user's browser waits for the execution of the PHP script to complete, that is, the status bar of the user's browser is always displayed in load.
Of course, you can also use other similar principles, such as script tags and so on.

The fourth method:


Popen ()

Resource Popen (String command, string mode);

Opens a pipeline that points to a process that is generated by the execution of a derived command command. Opens a pipeline that points to a process that is generated by the execution of a derived command command.

So you can call it, but ignore its output.

Pclose (Popen ("/home/xinchen/backend.php &", ' R '));

This method avoids the disadvantage of the first method and is also very fast. However, the problem is that this method cannot request another webservice through the HTTP protocol, only local script files can be executed. And can only be opened one way, unable to wear a large number of parameters to the called script.
And if, when the traffic is very high, there will be a lot of process. If you use external resources, consider the competition yourself.

The 5th method:

Using Curl
This method, set Curopt_timeout to 1 (minimum is 1, depressed). In other words, the client must wait at least 1 seconds.

$ch = Curl_init (); $curl _opt = Array (curlopt_url, ' http://www.example.com/backend.php ',                            curlopt_returntransfer, 1 ,                            curlopt_timeout, 1,); Curl_setopt_array ($ch, $curl _opt); curl_exec ($ch); Curl_close ($ch);

The Sixth method:

Using Fsockopen
This method should be the perfect one, but the downside is that you need to spell out the header part of HTTP yourself.

$fp = Fsockopen ("www.example.com", $errno, $errstr, +), if (! $fp) {    echo "$errstr ($errno) <br/>n";} else { c4/> $out = "Get/backend.php/http/1.1rn";    $out. = "HOST:WWW.EXAMPLE.COMRN";    $out. = "Connection:closernrn";    Fwrite ($fp, $out);    /* Ignore execution result while (!feof ($fp)) {echo fgets ($fp, 128);} *    /fclose ($FP);}

Summarize:

The above six methods are implemented in PHP asynchronous invocation of multi-threaded instances, each method has its characteristics, can be based on their own needs to choose the right way!

Related recommendations;

Introduction to three ways of implementing PHP multithreaded simulation


PHP Multi-Threading Implementation Example


PHP Multithreading One Implementation method-shell


php Multithreading Small Case

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.