Summary of several methods to try program concurrency in PHP programming, php programming _ PHP Tutorial

Source: Internet
Author: User
Tags php session
Summary of several methods of program concurrency testing in PHP Programming: php programming. In PHP programming, I will summarize several methods of program concurrency. in this article, I will summarize five concurrent methods in php Programming: 1. curl_multi_init refers to the summary of several methods to try program concurrency in Allowstheprocessing PHP programming.

This article summarizes five concurrency methods in PHP programming:
1. curl_multi_init
This document describes Allows the processing of multiple cURL handles asynchronously. it is indeed asynchronous. Here, we need to understand the select method. in this document, Blocks until there is activity on any of the curl_multi connections .. You can understand the common asynchronous models. select and epoll are all famous.

<?php// build the inpidual requests as above, but do 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 when all are 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);

Here, I set the result to exit the loop and delete the curl resource to cancel the http request.

2. swoole_client
Swoole_client provides the asynchronous mode. I forgot this. Here, the sleep method requires the swoole version to be greater than or equal to 1.7.21. I have not yet upgraded to this version, so you can exit directly.

<? Php $ client = new swoole_client (SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC); // set the 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 "; 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" ;}); // initiate a network Connection $ client-> connect ('2017. 207.95.145 ', 80, 1 );

3. process
Ah, I almost forgot swoole_process. I don't need the pcntl module here. However, after writing, we found that this is not actually an interruption of the request, but a first-served read, ignoring the subsequent return values.

<? Php $ workers = []; $ worker_num = 3; // number of created processes $ 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;} foreach ($ workers as $ pid => $ process) {// The sub-process will also contain this event swoole_event_add ($ process-> pipe, function ($ pipe) use ($ process, $ 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 prompts that ZTS must be enabled during php compilation, so it seems that the thread safe version is required for use. in wamp, php is exactly TS, and a dll is directly stored. the instructions in this document are copied to the corresponding directory and tested in win. I haven't fully understood it yet. I found that the pthreads and POSIX pthreads of php are completely different. The code is a little bad. you need to take a look at the documentation and try it out.

<?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
Write asynchronous code in synchronous mode:

<?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, 1000)) {         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->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, $port, $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 explanation:

With the built-in array capability of PHP, simple "time-out management" is implemented, with millisecond as the precision of time sharding;
Encapsulate the AsyncSendRecv interface. the call is more natural, such as yield AsyncSendRecv;
Add Exception as the error handling mechanism, and add ret_code for demonstration only.

Articles you may be interested in:
  • Php session lock and concurrency
  • Php solves the problem of inventory negative numbers caused by high-traffic concurrent warehouse receiving such as flash sales and flash sales.
  • Php automatically generates thumbnails based on URLs and handles high concurrency issues
  • Php concurrent read/write file conflict solution
  • Solutions to MYSQL stress caused by php concurrency
  • Code of a PHP concurrent access instance
  • PHP curl concurrency best practices code sharing
  • How PHP solves the problems of high website traffic and high concurrency
  • Nginx + PHP (FastCGI) build high concurrency WEB server (automatic installation script) Second Edition
  • PHP implementation code for common locks and locks under concurrency

Summary This article summarizes five concurrency methods in PHP Programming: 1. the curl_multi_init document describes Allows the processing...

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.