PHP编程中尝试程序并发的几种方式总结


Posted in PHP onMarch 21, 2016

本文大约总结了PHP编程中的五种并发方式:
1.curl_multi_init
文档中说的是 Allows the processing of multiple cURL handles asynchronously. 确实是异步。这里需要理解的是select这个方法,文档中是这么解释的Blocks until there is activity on any of the curl_multi connections.。了解一下常见的异步模型就应该能理解,select, epoll,都很有名

<?php
// build the individual requests as above, but do not execute them
$ch_1 = curl_init('https://3water.com/');
$ch_2 = curl_init('https://3water.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 handles
curl_multi_remove_handle($mh, $ch_1);
curl_multi_remove_handle($mh, $ch_2);
curl_multi_close($mh);

这里我设置的是,select得到结果,就退出循环,并且删除 curl resource, 从而达到取消http请求的目的。

2.swoole_client
swoole_client提供了异步模式,我竟然把这个忘了。这里的sleep方法需要swoole版本大于等于1.7.21, 我还没升到这个版本,所以直接exit也可以。

<?php
$client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC);
//设置事件回调函数
$client->on("connect", function($cli) {
  $req = "GET / HTTP/1.1\r\n
  Host: 3water.com\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";
});
//发起网络连接
$client->connect('183.207.95.145', 80, 1);

3.process
哎,竟然差点忘了 swoole_process, 这里就不用 pcntl 模块了。但是写完发现,这其实也不算是中断请求,而是哪个先到读哪个,忽视后面的返回值。

<?php

$workers = [];
$worker_num = 3;//创建的进程数
$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){
  //子进程也会包含此事件
  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
编译pthreads模块时,提示php编译时必须打开ZTS, 所以貌似必须 thread safe 版本才能使用. wamp中多php正好是TS的,直接下了个dll, 文档中的说明复制到对应目录,就在win下测试了。 还没完全理解,查到文章说 php 的 pthreads 和 POSIX pthreads是完全不一样的。代码有些烂,还需要多看看文档,体会一下。

<?php
class Foo extends Stackable {
  public $url;
  public $response = null;
  public function __construct(){
    $this->url = 'https://3water.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
以同步方式书写异步代码:

<?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(); 
 
?>

代码解读:

借助PHP内置array能力,实现简单的“超时管理”,以毫秒为精度作为时间分片;
封装AsyncSendRecv接口,调用形如yield AsyncSendRecv(),更加自然;
添加Exception作为错误处理机制,添加ret_code亦可,仅为展示之用。

PHP 相关文章推荐
php下实现伪 url 的超简单方法[转]
Sep 24 PHP
php代码把全角数字转为半角数字
Dec 10 PHP
php 多关键字 高亮显示实现代码
Apr 23 PHP
php加水印的代码(支持半透明透明打水印,支持png透明背景)
Jan 17 PHP
PHP的基本常识小结
Jul 05 PHP
php从数组中随机选择若干不重复元素的方法
Mar 14 PHP
PHP模板引擎Smarty中的保留变量用法分析
Apr 11 PHP
php数组函数array_walk用法示例
May 26 PHP
PHP中的表达式简述
May 29 PHP
php正则去除网页中所有的html,js,css,注释的实现方法
Nov 03 PHP
10个值得深思的PHP面试题
Nov 14 PHP
php微信公众号开发之快递查询
Oct 20 PHP
PHP的Laravel框架中使用消息队列queue及异步队列的方法
Mar 21 #PHP
Zend Framework框架之Zend_Mail实现发送Email邮件验证功能及解决标题乱码的方法
Mar 21 #PHP
Zend Framework教程之Zend_Form组件实现表单提交并显示错误提示的方法
Mar 21 #PHP
Zend Framework实现多文件上传功能实例
Mar 21 #PHP
Zend Framework入门之环境配置及第一个Hello World示例(附demo源码下载)
Mar 21 #PHP
Zend Framework教程之连接数据库并执行增删查的方法(附demo源码下载)
Mar 21 #PHP
Zend Framework框架教程之Zend_Db_Table_Rowset用法实例分析
Mar 21 #PHP
You might like
很好用的PHP数据库类
2009/05/27 PHP
linux下为php添加curl扩展的方法
2011/07/29 PHP
探讨:php中在foreach中使用foreach ($arr as &amp;$value) 这种类型的解释
2013/06/24 PHP
ThinkPHP验证码和分页实例教程
2014/08/22 PHP
解析WordPress中的post_class与get_post_class函数
2016/01/04 PHP
Yii隐藏URL中index.php的方法
2016/07/12 PHP
PHP Callable强制指定回调类型的方法
2016/08/30 PHP
jquery实现带二级菜单的导航示例
2014/04/28 Javascript
js 通过html()及text()方法获取并设置p标签的显示值
2014/05/14 Javascript
手机开发必备技巧:javascript及CSS功能代码分享
2015/05/25 Javascript
jQuery动画效果实现图片无缝连续滚动
2016/01/12 Javascript
node.js缺少mysql模块运行报错的解决方法
2016/11/13 Javascript
巧用数组制作图片切换js代码
2016/11/29 Javascript
jQuery联动日历的实例解析
2016/12/02 Javascript
浅谈Node.js:Buffer模块
2016/12/05 Javascript
vue+django实现一对一聊天功能的实例代码
2019/07/17 Javascript
微信小程序点击生成朋友圈分享图(遇到的坑)
2020/06/17 Javascript
jQuery实现回到顶部效果
2020/10/19 jQuery
新手该如何学python怎么学好python?
2008/10/07 Python
python使用clear方法清除字典内全部数据实例
2015/07/11 Python
放弃 Python 转向 Go语言有人给出了 9 大理由
2017/10/20 Python
Pandas读取MySQL数据到DataFrame的方法
2018/07/25 Python
如何利用Boost.Python实现Python C/C++混合编程详解
2018/11/08 Python
PyTorch预训练的实现
2019/09/18 Python
Python使用lambda抛出异常实现方法解析
2020/08/20 Python
python 使用tkinter+you-get实现视频下载器
2020/11/17 Python
Crocs卡骆驰洞洞鞋日本官方网站:Crocs日本
2016/08/25 全球购物
德国柯吉澳趣味家居:Koziol
2017/08/24 全球购物
英国现代家具和装饰网站:PN Home
2018/08/16 全球购物
酒店门卫岗位职责
2013/12/29 职场文书
整顿机关作风心得体会
2014/09/10 职场文书
领导班子作风建设年个人整改措施
2014/09/29 职场文书
文明上网主题班会
2015/08/14 职场文书
原来实习报告是这样写的呀!
2019/07/03 职场文书
用python实现监控视频人数统计
2021/05/21 Python
如何解决php-fpm启动不了问题
2021/11/17 PHP