最近需要对3W台服务器进行下发脚本,如果一个一个执行,时间大约在2个小时,特别的慢,于是修改程序,采用php的多线程去分发,大概在10分钟左右完成,下面记录下这次的经验和理解:

  我所理解的php的多线程实现的方式有两种,下面是官方的介绍:

  1、官方的介绍:(转载自张宴的博客)

  到php5.3以上的版本,php才算是真正的支持多线程,使用的是pthreads的扩展,php在处理多个循环的任务的时候,能够大大的缩短程序的执行时间。

  大多数网站的性能瓶颈,不在php的服务器上,而是在mysql服务器上。因为可以通过横向的增加服务器或者是cpu的核数来应对。如果用Mysql数据库,一条联合查询可能处理玩很复杂的业务逻辑,但是遇到大并发量的查询,服务器可能就会瘫痪。因此我们可以使用NoSQL数据库代替mysql服务器,一条很复杂的sql语句,可能需要好几条NOSQL语句来完成,但是遇到大量的并发的情况下,速度确实非常明显的。然后再加上php的多线程的使用,通过十个php的线程查询NOSQL,然后汇总返回结果输出,速度是非常之快的。

   PHP扩展下载:https://github.com/krakjoe/pthreads
  PHP手册文档:http://php.net/manual/zh/book.pthreads.php

  1、扩展的编译安装(Linux),编辑参数 --enable-maintainer-zts 是必选项:

 cd /Data/tgz/php-5.5.1
./configure --prefix=/Data/apps/php --with-config-file-path=/Data/apps/php/etc --with-mysql=/Data/apps/mysql --with-mysqli=/Data/apps/mysql/bin/mysql_config --with-iconv-dir --with-freetype-dir=/Data/apps/libs --with-jpeg-dir=/Data/apps/libs --with-png-dir=/Data/apps/libs --with-zlib --with-libxml-dir=/usr --enable-xml --disable-rpath --enable-bcmath --enable-shmop --enable-sysvsem --enable-inline-optimization --with-curl --enable-mbregex --enable-fpm --enable-mbstring --with-mcrypt=/Data/apps/libs --with-gd --enable-gd-native-ttf --with-openssl --with-mhash --enable-pcntl --enable-sockets --with-xmlrpc --enable-zip --enable-soap --enable-opcache --with-pdo-mysql --enable-maintainer-zts
make clean
make
make install unzip pthreads-master.zip
cd pthreads-master
/Data/apps/php/bin/phpize
./configure --with-php-config=/Data/apps/php/bin/php-config
make
make install
vi /Data/apps/php/etc/php.ini
extension = "pthreads.so"

  2、给出一段PHP多线程、与For循环,抓取百度搜索页面的PHP代码示例:

 <?php
  class test_thread_run extends Thread
  {
      public $url;
      public $data;       public function __construct($url)
      {
          $this->url = $url;
      }       public function run()
      {
          if(($url = $this->url))
          {
              $this->data = model_http_curl_get($url);
          }
      }
  }   function model_thread_result_get($urls_array)
  {
      foreach ($urls_array as $key => $value)
      {
          $thread_array[$key] = new test_thread_run($value["url"]);
          $thread_array[$key]->start();
      }       foreach ($thread_array as $thread_array_key => $thread_array_value)
      {
          while($thread_array[$thread_array_key]->isRunning())
          {
              usleep(10);
          }
          if($thread_array[$thread_array_key]->join())
          {
              $variable_data[$thread_array_key] = $thread_array[$thread_array_key]->data;
          }
      }
      return $variable_data;
  }   function model_http_curl_get($url,$userAgent="")
  {
      $userAgent = $userAgent ? $userAgent : 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2)';
      $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, $userAgent);
      $result = curl_exec($curl);
      curl_close($curl);
      return $result;
  }   for ($i=0; $i < 100; $i++)
  {
      $urls_array[] = array("name" => "baidu", "url" => "http://www.baidu.com/s?wd=".mt_rand(10000,20000));
  }   $t = microtime(true);
  $result = model_thread_result_get($urls_array);
  $e = microtime(true);
  echo "多线程:".($e-$t)."\n";   $t = microtime(true);
  foreach ($urls_array as $key => $value)
  {
      $result_new[$key] = model_http_curl_get($value["url"]);
  }
  $e = microtime(true);
  echo "For循环:".($e-$t)."\n";
?>

  上述是官方给的一个php多线程的一个扩展,由于需要重新编译,因此自己没有进行试验,但其实本质都是在linux中开启多个线程来进行处理。

2、下面说下我自己搞得伪造的php的多线程的实例:

下面是一段测试的代码:

for.php

 <?php
$start = microtime(true);
for($i=0;$i<5000;$i++){
$cmd = "php ./test.php &"; -----// 主要是这个,使用php执行,将程序放到后台执行,不等待返回结果,再次继续循环,类似于异步的方式,生成多个php的线程。
$fp = popen($cmd,"r");
}
fclose($fp);
$end = microtime(true); echo $end-$start; ?>

test.php(简单的显示phpinfo的信息):

 <?php
phpinfo();
?>
采用多线程的执行的时间:32.89448595047
采用普通的执行的时间:85.191102027893

执行循环的次数越大,这种时间差就很明显。

ps:我们可以写一个python或者shell的脚本,来实时的检测php的进程数的变化:

 #!/usr/bin/env/ python
import os
from time import sleep while 1:
os.system("ps -aux|grep php|wc -l");
sleep(1); 上面是一个简单的统计php进程数的一个脚本,在shell界面执行的时候,可以将输出定位到一个文件中。

记录:

并发的最大记录数:

  之前在公司的机器上跑了一个多线程的程序,

  机器的配置是48G内存   6个CPU,

  一次并发的线程数大概在3000左右,超过4000,会造成内存溢出,机器挂死。这是最大的并发线程数。

但是我们在线上跑的时候,为了安全,一定要记住最多我们也就并发几十个到100个进程,如果超出了范围,会发生数据的丢失和一些诡异的现象发生。

关于php多线程的记录的更多相关文章

  1. java定时器和多线程实践记录

    这几天因为需要测试mongodb读写分离的问题,因此写了个定时查询程序,并且用到了多线程,以达到定时启动多个线程查询数据库的效果,下边代码记录备忘: package timmer; import ja ...

  2. python多线程学习记录

    1.多线程的创建 import threading t = t.theading.Thread(target, args--) t.SetDeamon(True)//设置为守护进程 t.start() ...

  3. GCD 多线程 ---的记录 iOS

    先写一个GCD static UserInfoVoModel *userInfoShare = nil; +(instancetype)shareUserInfoVoModel { static di ...

  4. C# 面向切面编程--监控日志记录方案

    背景:现在公司整体在做监控平台,要求把各个部分的细节都记录下来,在前台页面上有所显示,所以现在需要做的就是一个监控日志的记录工作,今天讲的就是渲染监控日志的例子. 现状:当前的渲染程序没有为监控日志记 ...

  5. C# 各种帮助类大全

    前言 此篇专门记录一些常见DB帮助类及其他帮助类,以便使用时不用重复造轮子. DBHelper帮助类 ①首当其冲的就是Sql Server帮助类,创建名为DbHelperSQL 的类 ,全部代码如下: ...

  6. trinitycore 魔兽服务器源码分析(一) 网络

    trinitycore是游戏服务器的开源代码 许多玩家使用魔兽的数据来进行测试 ,使用它来假设魔兽私服. 官方网址  https://www.trinitycore.org/ 类似的还有mangos ...

  7. C#类库帮助类

    前言 此篇专门记录一些常见DB帮助类及其他帮助类,以便使用时不用重复造轮子. DBHelper帮助类 ①首当其冲的就是Sql Server帮助类,创建名为DbHelperSQL 的类 ,全部代码如下: ...

  8. WINDOWS-API:关于线程CreateThread,_beginthead(_beginthreadex),AfxBeginThread

    [转]windows多线程编程CreateThread,_beginthead(_beginthreadex)和AfxBeginThread的区别 在Windows的多线程编程中,创建线程的函数主要有 ...

  9. 剖析虚幻渲染体系(14)- 延展篇:现代渲染引擎演变史Part 1(萌芽期)

    目录 14.1 本篇概述 14.1.1 游戏引擎简介 14.1.2 游戏引擎模块 14.1.3 游戏引擎列表 14.1.3.1 Unreal Engine 14.1.3.2 Unity 14.1.3. ...

随机推荐

  1. HDU 1508 DP

    题意:规定一个数列 = {这个数的质因子只能包括2,3,5,7},求第n个数字是多少: 思路:暴力打表,然后只粘数据,虽然过了,但是正解其实是DP,每一个数字都是由某一个该数列里的某一个数字乘以2,3 ...

  2. iOS获取设备信息

        NSString *strName = [[UIDevice currentDevice] name]; // Name of the phone as named by user       ...

  3. C#中用schema验证xml的合法性

    class ValidateXML { public string ErrString = string.Empty; public void ValidationEventCallBack(Obje ...

  4. Merge Intervals

    Given a collection of intervals, merge all overlapping intervals. For example,Given [1,3],[2,6],[8,1 ...

  5. 我的STL之旅 MyStack

    #include<iostream> #include<cstdio> #include<cstring> #include<algorithm> us ...

  6. unity, itween, closed path

  7. SQL阻塞原因造成系统多功能无响应的分析解决思路

    最近遇到一个sqlserver项目,月底会出现多个财务相关功能出现不定期操作无响应问题 通过查询SQL阻塞信息,定位到阻塞源头spid.该会话的状态.等待事件及执行的SQL脚本 根据spid查询该会话 ...

  8. How to Allow MySQL Client to Connect to Remote MySql

    How to Allow MySQL Client to Connect to Remote MySQ By default, MySQL does not allow remote clients ...

  9. 过滤HTML代码

    public static string FilterHtml(string string_include_html) { string[] HtmlRegexArr ={ #region Html ...

  10. jQuery使用示例详解

    [jquery引用字段] <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv ...