About the processing of multi-threading in PHP

Source: Internet
Author: User
Tags echo date php multithreading phpinfo usleep vc9

The following is about the PHP multithreading problem, php pthreads extension and curl_multi_init function, when you encounter such problems will not be solved, see how others are solved.

Windows install PHP Real multi-threaded extension pthreads tutorial

Extension Address: http://docs.php.net/manual/zh/book.pthreads.php
Precautions
php5.3 or more, and is a thread-safe version. The compilers used by Apache and PHP must be consistent.
Thread-safe version is phpinfo () to view thread safety as enabled.
You can see the compiler that is used by phpinfo () to view the compiler item. my: MSVC9 (Visual C + + 2008).
Use environment
32-bit Windows XP Sp3,wampserver2.2d (PHP5.3.10-VC9 + apache2.2.21-vc9).
First, download pthreads extension
Download Address: Http://windows.php.net/downloads/pecl/releases/pthreads
According to my environment, I downloaded the pthreads-2.0.8-5.3-ts-vc9-x86.
2.0.8 represents the version of Pthreads.
5.3 Represents the version of PHP.
TS indicates that PHP wants a thread-safe version.
Vc9 means that PHP is compiled by the Visual C + + 2008 compiler.
The x86 represents a 32-bit

Second, install pthreads extension
Copy the Php_pthreads.dll to the directory bin\php\ext\ below. (I path D:\wamp\bin\php\php5.3.10\ext)
Copy the PthreadVC2.dll to the directory bin\php\ below. (I path D:\wamp\bin\php\php5.3.10)
Copy the PthreadVC2.dll to the directory C:\windows\system32 below.
Open php config file php.ini. Add Extension=php_pthreads.dll to the back.
Tips! The Windows system needs to include the path of the PthreadVC2.dll into the PATH environment variable. My Computer---> Right---> Properties---> Advanced---> Environment variables---> System variables---> Find---> Edit---> Named path At the end of the variable value, add the full path to the PthreadVC2.dll (my C:\WINDOWS\system32\pthreadVC2.dll).
Third, test pthreads extension

Class AsyncOperation extends \thread {public    function __construct ($arg) {        $this->arg = $arg;    }    Public Function Run () {        if ($this->arg) {            printf ("Hello%s\n", $this->arg);        }    }} $thread = new AsyncOperation ("World"), if ($thread->start ())    $thread->join (); >

Running the above code appears Hello world, indicating that the pthreads extension was successfully installed!

Attach a Thinkphp3.2.2 simple example

<?phpnamespace Home\controller;class Test extends \thread {public $url;        public $result;    Public function __construct ($url) {$this->url = $url; Public Function Run () {if ($this->url) {$this->result = model_http_curl_get ($this->u        RL);      }}}function Model_http_curl_get ($url) {$curl = Curl_init ();      curl_setopt ($curl, Curlopt_url, $url);      curl_setopt ($curl, Curlopt_returntransfer, 1);      curl_setopt ($curl, Curlopt_timeout, 5); curl_setopt ($curl, Curlopt_useragent, ' mozilla/4.0 (compatible; MSIE 7.0;      Windows NT 5.2) ');      $result = curl_exec ($curl);      Curl_close ($curl);  return $result; }for ($i = 0; $i < $i + +) {$urls [] = ' http://www.baidu.com/s?wd= '. Rand (10000, 20000);    /* Multithreaded Speed Test */$t = Microtime (True); foreach ($urls as $key = = $url) {$workers [$key] = new test ($url); $workers [$key]->start ();} foreach ($workers as $key = + $worker) {while ($workers [$key]->isrunNing ()) {usleep (100);    } if ($workers [$key]->join ()) {Dump ($workers [$key]->result); }} $e = Microtime (true); echo "Multithreading Time:". ($e-$t). "  Seconds <br> "; /* Single-threaded speed Test */$t = Microtime (True); foreach ($urls as $key = = $url) {dump (Model_http_curl_get ($url));} $e = Microtime (true); echo "For loop time:". ($e-$t). " Seconds <br> ";

The test results are as follows:

Multithreading time: 2.83717107772827 seconds
For loop time: 10.9415860176086 seconds

Curl_multi_init ()

<?phpecho date ("Y-m-d h:m:s", Time ()), echo "", Echo Floor (Microtime () *1000), echo "<br>", $mtime = Explode ("", Microtime ()); $mtime = $mtime [1]. ($mtime [0] * +); $mtime 2 = Explode (".", $mtime); $mtime = $mtime 2[0]; Echo $mtime, echo "<br>", $urls =array (' http://www.a.com ', ' http://www.b.com ', ' http://www.c.com ', ' http:// Www.d.com ', ' http://www.e.com '); Print_r (Async_get_url ($urls)); [0]=>example1,[1]=>example2echo "<br>", Echo date ("Y-m-d h:m:s", Time ()), echo "", Echo Floor (Microtime () *1000); echo "<br>", $mtime _ = Explode ("", Microtime ()); $mtime _ = $mtime _[1]. ($mtime _[0] * +), $mtime 2_ = Explode (".", $mtime _); $mtime _ = $mtime 2_[0]; echo $mtime _;echo "<br>", Echo $mtime _-$mtime, function Async_get_url ($url _array, $wait _usec = 0) {if (!is_array ($ Url_array)) return false; $wait _usec = Intval ($wait _usec); $data = Array (); $handle = Array (); $running = 0; $mh = curl_multi_i NIT (); Multi Curl handler$i = 0;foreach ($url _array as $url) {$ch = Curl_init (); curl_setopT ($ch, Curlopt_url, $url); curl_setopt ($ch, Curlopt_returntransfer, 1); Return don ' t printcurl_setopt ($ch, Curlopt_timeout, 30); curl_setopt ($ch, Curlopt_useragent, ' mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0) ');  curl_setopt ($ch, curlopt_followlocation, 1); 302 redirectcurl_setopt ($ch, Curlopt_maxredirs, 7);  Curl_multi_add_handle ($MH, $ch); Put curl resource in multi curl handler $handle [$i + +] = $ch;}  /* Execute */do {curl_multi_exec ($MH, $running), if ($wait _usec > 0)/* How long each connect will take/usleep ($wait _usec); 250000 = 0.25 sec} while ($running > 0);/* Read data */foreach ($handle as $i = = $ch) {$content = Curl_multi_getcon  Tent ($ch); $data [$i] = (Curl_errno ($ch) = = 0)?  $content: false;}  /* Remove handle*/foreach ($handle as $ch) {Curl_multi_remove_handle ($MH, $ch);  } curl_multi_close ($MH);  return $data;} ?>

About Curl_multi_init ()

In general, when you think about using Curl_multi_init (), the goal is to request multiple URLs at the same time, instead of one in turn, or curl_init ().

However, in the use of Curl_multi, you may encounter high CPU consumption, the page suspended animation and other phenomena, you can see how to solve the Curl_multi cause the Web page suspended animation problem

The steps for using Curl_multi are summarized as follows:

First step: Call Curl_multi_init
Step two: Loop call Curl_multi_add_handle
It is important to note that the second parameter of Curl_multi_add_handle is a sub-handle from Curl_init.
Step three: Continue calling Curl_multi_exec
Fourth step: Loop call Curl_multi_getcontent as needed to get results
Fifth step: Call Curl_multi_remove_handle, and call curl_close for each word handle
Sixth step: Call Curl_multi_close

Explanation of function functions:

Curl_multi_init ()
Initializes a curl batch handle resource.

Curl_multi_add_handle ()
Adds a separate curl handle resource to the Curl batch session. The Curl_multi_add_handle () function has two parameters, the first parameter represents a curl batch handle resource, and the second parameter represents a separate curl handle resource.

Curl_multi_exec ()
Parsing a curl batch handle, the Curl_multi_exec () function has two parameters, the first parameter represents a batch handle resource, and the second parameter is a reference value parameter that represents the number of individual curl handle resources remaining to be processed.

Curl_multi_remove_handle ()
Removes a handle resource from the Curl batch handle resource, the Curl_multi_remove_handle () function has two parameters, the first parameter represents a curl batch handle resource, and the second parameter represents a separate curl handle resource.

Curl_multi_close ()
Closes a batch handle resource.

Curl_multi_getcontent ()
Returns the text stream of the obtained output, in the case of a curlopt_returntransfer set.

Curl_multi_info_read ()
Gets the related transport information for the currently resolved curl.

This article PHP multi-threaded issues to share, I hope to be helpful to everyone, if there are questions you can express comments or suggestions. Later small series will also share a lot of articles on this kind, please pay attention 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.