PHP programming in several ways to try the concurrency of the summary, PHP programming _php Tutorial

Source: Internet
Author: User
Tags php session

PHP programming in several ways to try the concurrency of the summary, PHP programming


This article summarizes approximately five types of concurrency in PHP programming:
1.curl_multi_init
The document says allows the processing of multiple CURL handles asynchronously. is indeed asynchronous. What needs to be understood here is the Select method, which is explained in the document blocks until there is the activity on any of the Curl_multi connections. Understanding the common asynchronous model should be understandable, select, Epoll, are famous

<?php//build the individual requests as above, but does not execute them$ch_1 = curl_init (' http://www.bkjia.com/'); $ch _2 = Curl_init (' http://www.bkjia.com/'); curl_setopt ($ch _1, Curlopt_returntransfer, True); curl_setopt ($ch _2, Curlopt_ Returntransfer, True);//Build the Multi-curl handle, adding both $ch $mh = Curl_multi_init (); Curl_multi_add_handle ($MH, $  ch_1) Curl_multi_add_handle ($MH, $ch _2);//execute all queries simultaneously, and continue if all is complete$running = null;do {  curl_multi_exec ($MH, $running);  $ch = Curl_multi_select ($MH);  if ($ch!== 0) {    $info = Curl_multi_info_read ($MH);    if ($info) {      var_dump ($info);      $response _1 = curl_multi_getcontent ($info [' handle ']);      echo "$response _1 \ n";      Break;}}}  while ($running > 0);//close the Handlescurl_multi_remove_handle ($MH, $ch _1); Curl_multi_remove_handle ($MH, $ch _2); Curl_multi_close ($MH);

What I'm setting here is that the select gets the result, exits the loop, and removes the curl resource, which is the purpose of canceling the HTTP request.

2.swoole_client
Swoole_client provided an asynchronous pattern, and I forgot about it. The sleep method here requires that the Swoole version is greater than or equal to 1.7.21, I have not risen to this version, so the direct exit can also.

<?php$client = new Swoole_client (swoole_sock_tcp, Swoole_sock_async);//Set Event callback function $client->on ("Connect", function ($CLI) {  $req = "get/http/1.1\r\n  host:www.jb51.net\r\n  connection:keep-alive\r\n  cache-control:no-cache\r\n  pragma:no-cache\r\n\r\n ";  for ($i =0; $i < 3; $i + +) {    $cli->send ($req);  }}); $client->on ("Receive", Function ($CLI, $data) {  echo "Received:". $data. " \ n ";  Exit (0);  $cli->sleep (); Swoole >= 1.7.21}); $client->on ("Error", function ($CLI) {  echo "Connect failed\n";}); $client->on ("Close", function ($CLI) {  echo "Connection close\n";}); /Initiating network connection $client->connect (' 183.207.95.145 ', 80, 1);

3.process
Ah, unexpectedly almost forget swoole_process, here will not pcntl module. But after writing the discovery, this is actually not the interruption of the request, but which first to read which, ignoring the back of the return value.

<?php$workers = []; $worker _num = 3;//The number of processes created $finished = false; $lock = new Swoole_lock (Swoole_mutex)  for ($i =0; $i < $worker _num; $i + +) {$process = new swoole_process (' process ');  $process->usequeue ();  $pid = $process->start (); $workers [$pid] = $process;} The foreach ($workers as $pid + $process) {///Sub-process also contains this event Swoole_event_add ($process->pipe, function ($pipe) use ($proces    S, $lock, & $finished) {$lock->lock ();      if (! $finished) {$finished = true;      $data = $process->read (); echo "RECV:". $data.    Php_eol;  } $lock->unlock (); });}  function process (swoole_process $process) {$response = ' http response ';  $process->write ($response); echo $process->pid, "\ T", $process->callback. Php_eol;}  for ($i = 0; $i < $worker _num; $i + +) {$ret = Swoole_process::wait ();  $pid = $ret [' pid ']; echo "Worker Exit, pid=". $pid. Php_eol;} 

4.pthreads
When compiling the Pthreads module, it is suggested that PHP must open zts when compiling, so it seems necessary to use the thread safe version. Wamp PHP is just the TS, directly under a DLL, the instructions in the document copied to the corresponding directory, the win under test. Not fully understood, the article said that PHP pthreads and POSIX pthreads is completely different. The code is a bit rotten, you need to look at the document more, experience.

<?phpclass Foo extends Stackable {public  $url;  public $response = null;  Public Function __construct () {    $this->url = ' http://www.bkjia.com ';  }  Public Function Run () {}}class Process extends Worker {  private $text = "";  Public function __construct ($text, $object) {    $this->text = $text;    $this->object = $object;  }  Public Function run () {while    (Is_null ($this->object->response)) {      print ' Thread {$this->text} is Running\n ";      $this->object->response = ' http response ';      Sleep (1);}}  $foo = new Foo (), $a = new process ("a", $foo); $a->start (); $b = new Process ("B", $foo); $b->start (); Echo $foo Response

5.yield
To write asynchronous code in a synchronous manner:

<?php class Asyncserver {protected $handler;   protected $socket;   protected $tasks = [];    protected $timers = [];      Public function __construct (callable $handler) {$this->handler = $handler;     $this->socket = socket_create (Af_inet, Sock_dgram, SOL_UDP); if (! $this->socket) {die (Socket_strerror (Socket_last_error ()).     \ n "); } if (!socket_set_nonblock ($this->socket)) {die (Socket_strerror (Socket_last_error ()).     \ n "); } if (!socket_bind ($this->socket, "0.0.0.0", 1234)) {die (Socket_strerror (Socket_last_error ()). "     \ n ");       }} Public Function Run () {while (true) {$now = Microtime (True) * 1000;         foreach ($this->timers as $time = + $sockets) {if ($time > $now) break;           foreach ($sockets as $one) {list ($socket, $coroutine) = $this->tasks[$one];           unset ($this->tasks[$one]);           Socket_close ($socket); $coroutine->throw (New Exception ("TimeouT "));       } unset ($this->timers[$time]);       } $reads = Array ($this->socket);       foreach ($this->tasks as List ($socket)) {$reads [] = $socket;       } $writes = NULL;       $excepts = NULL;       if (!socket_select ($reads, $writes, $excepts, 0, +)) {continue;         } foreach ($reads as $one) {$len = Socket_recvfrom ($one, $data, 65535, 0, $ip, $port);           if (! $len) {//echo "Socket_recvfrom fail.\n";         Continue if ($one = = $this->socket) {//echo "[Run]request recvfrom succ.           Data= $data ip= $ip port= $port \ n ";           $handler = $this->handler;           $coroutine = $handler ($one, $data, $len, $ip, $port);             if (! $coroutine) {//echo "[run]everything is done.\n";           Continue           } $task = $coroutine->current (); echo "[Run]asynctask recv. Data= $task->data ip= $task->ip port= $task->port timeout= $task->timeout\n ";           $socket = Socket_create (Af_inet, Sock_dgram, SOL_UDP); if (! $socket) {//echo socket_strerror (Socket_last_error ()). "             \ n ";             $coroutine->throw (New Exception (Socket_strerror (Socket_last_error ()), Socket_last_error ());           Continue } if (!socket_set_nonblock ($socket)) {//echo socket_strerror (Socket_last_error ()). "             \ n ";             $coroutine->throw (New Exception (Socket_strerror (Socket_last_error ()), Socket_last_error ());           Continue           } socket_sendto ($socket, $task->data, $task->len, 0, $task->ip, $task->port);           $deadline = $now + $task->timeout;           $this->tasks[$socket] = [$socket, $coroutine, $deadline];         $this->timers[$deadline] [$socket] = $socket; } else {//echo "[Run]response recvfrom succ.           Data= $data ip= $ip port= $port \ n "; List ($socket, $coroutine, $deadline) = $this-&Gt;tasks[$one];           unset ($this->tasks[$one]);           unset ($this->timers[$deadline [$one]);           Socket_close ($socket);         $coroutine->send (Array ($data, $len));   }}}}} class Asynctask {public $data;   Public $len;   Public $ip;   Public $port;    Public $timeout;     Public function __construct ($data, $len, $ip, $port, $timeout) {$this->data = $data;     $this->len = $len;     $this->ip = $ip;     $this->port = $port;   $this->timeout = $timeout; }} function Asyncsendrecv ($req _buf, $req _len, $ip, $port, $timeout) {return new Asynctask ($req _buf, $req _len, $ip, $p ORT, $timeout); } function RequestHandler ($socket, $req _buf, $req _len, $ip, $port) {//echo "[RequestHandler] before yield asynctask.   req= $req _buf\n ";   try {list ($rsp _buf, $rsp _len) = (yield Asyncsendrecv ($req _buf, $req _len, "127.0.0.1", 2345, 3000));     } catch (Exception $ex) {$rsp _buf = $ex->getmessage (); $RSP _len = strlen ($RSP _buf);   echo "[Exception] $rsp _buf\n"; }//echo "[RequestHandler] after yield asynctask.   rsp= $rsp _buf\n "; Socket_sendto ($socket, $rsp _buf, $rsp _len, 0, $ip, $port); } $server = new Asyncserver (RequestHandler);  $server->run ();  ?>

Code interpretation:

With PHP built-in array capabilities, a simple "time-out management", with milliseconds as precision as the time shard;
Encapsulation Asyncsendrecv interface, call form like yield asyncsendrecv (), more natural;
Add exception as the error handling mechanism, add ret_code Also, for display purposes only.

Articles you may be interested in:

    • The lock and concurrency of the PHP session
    • PHP solves the problem of stock negative caused by high traffic and storage in the second-kill lottery
    • PHP automatically generates thumbnails based on URLs and handles high concurrency issues
    • The solution of concurrent read and write file conflicts in PHP
    • The solution to the strain on MySQL caused by PHP concurrency
    • A PHP concurrent Access instance code
    • PHP Curl concurrency Best Practices code sharing
    • How PHP solves the problem of large traffic and high concurrency of the website
    • nginx+php (FastCGI) build high concurrent Web server (automatic installation script) Second Edition
    • PHP specific implementation code for common locking and locks under concurrency

http://www.bkjia.com/PHPjc/1113733.html www.bkjia.com true http://www.bkjia.com/PHPjc/1113733.html techarticle PHP programming in a number of ways to try the concurrency of the summary, PHP programming This article about five kinds of concurrency in PHP programming: 1.curl_multi_init document is said allows the processing ...

  • Related Article

    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.