php专区

 首页 > php专区 > PHP应用 > 常用功能 > php多进程几个例子 - php高级应用

php多进程几个例子 - php高级应用

分享到:
【字体:
导读:
          php多进程这个东西先是在java中有不过现在高版本的php也支持多进程这个功能,但经过测试性能不如j(www phpfensi com)ava了希望后期有所提高了,下面我们一起来看看我整理了几个关于php多进程...

php多进程几个例子

php多进程这个东西先是在java中有不过现在高版本的php也支持多进程这个功能,但经过测试性能不如j(www.phpfensi.com)ava了希望后期有所提高了,下面我们一起来看看我整理了几个关于php多进程例子,希望能帮助你理解多线程.

php多进程的实现依赖于pcntl扩展,编译PHP的时候,可以加上’–enable-pcntl’或者也可以单独编译.

有三点需要注意:

1.子进程不在执行fork之前的代码,只是把父进程的内存状况复制一份新的,所以,关于子进程的个性化设置需要单独设置.

2.输出重定向,程序中使用echo,或造成命令行的混乱,影响分辨,可以用ob_start重定向到log文件,当然,你直接使用log是更好的办法,此实例中log文件,按照进程pid分组.

3.父进程没有代码执行,将可能提前退出,子进程可能成为孤儿进程.

demo接收:

用10个子进程来处理输出任务,任务总量是1000,然后,按照任务数平均分到十个子进程当中去,代码如下:

  1.  //输出重定向到log文件                    
  2. function echo_to_log($content){ 
  3.     global $current_pid
  4.     $logfile =  __FILE__ . $current_pid .  '.log'
  5.     $fp = fopen($logfile'a+'); 
  6.     fwrite($fp$content); 
  7.     fclose($fp); 
  8.                                                                                   
  9. ob_start('echo_to_log'); 
  10. //获取当前进程pid 
  11. $current_pid = getmypid(); 
  12. $fork_nums = 10; 
  13. $total = 1000; 
  14.                                                                                   
  15. for($i = 0; $i < $fork_nums$i++){ 
  16.     $pid = pcntl_fork(); 
  17.     //等于0时,是子进程 
  18.     if($pid == 0){ 
  19.         $current_pid = $pid
  20.         do_task($i); 
  21.      //大于0时,是父进程,并且pid是产生的子进程的PID 
  22.     } else if($pid > 0) { 
  23.     } 
  24.                                                                                   
  25. //任务函数 
  26. function do_task($task_num){ 
  27.     global $total
  28.     $start = $total / 10 * $task_num
  29.     $end = $total / 10 * ($task_num + 1); 
  30.     for(;$start<$end;$start++){ 
  31.         echo $task_num . " " . $start . "\n"
  32.     } 
  33.     //子进程执行完任务以后终止,当然你可以返回主进程的代码部分做相关操作。 
  34.     exit(); 

多进程控制的框架代码,留着备查,代码如下:

  1. declare(ticks=1); 
  2. function sigHandler($signal
  3.     echo "a child exited\n"
  4. pcntl_signal(SIGCHLD, sigHandler, false); 
  5. echo "this is " . posix_getpid() . PHP_EOL; 
  6. for($i=0; $i<3; $i++) 
  7.     $pid = pcntl_fork(); 
  8.     if($pid == -1)  
  9.     {    
  10.         echo 'fork failed ' . PHP_EOL; 
  11.     }    
  12.     else if($pid
  13.     {    
  14.     }    
  15.     else 
  16.     {    
  17.         $pid = posix_getpid(); 
  18.         echo 'child ' . $pid . ' ' . time() . PHP_EOL; 
  19.         sleep(rand(2,5)); 
  20.         echo 'child ' . $pid . ' done ' . time() . PHP_EOL; 
  21.         exit(0); 
  22.     }    
  23. do 
  24.     $pid = pcntl_wait($status);  
  25.     echo 'child quit ' . $pid . PHP_EOL; 
  26. }while($pid > 0);  
  27. echo 'parent done' . PHP_EOL; 

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

  1.   class test_thread_run extends Thread  
  2.   { 
  3.       public $url
  4.       public $data
  5.  
  6.       public function __construct($url
  7.       { 
  8.           $this->url = $url
  9.       } 
  10.  
  11.       public function run() 
  12.       { 
  13.           if(($url = $this->url)) 
  14.           { 
  15.               $this->data = model_http_curl_get($url); 
  16.           } 
  17.       } 
  18.   } 
  19.  
  20.   function model_thread_result_get($urls_array)  
  21.   { 
  22.       foreach ($urls_array as $key => $value)  
  23.       { 
  24.           $thread_array[$key] = new test_thread_run($value["url"]); 
  25.           $thread_array[$key]->start(); 
  26.       } 
  27.  
  28.       foreach ($thread_array as $thread_array_key => $thread_array_value)  
  29.       { 
  30.           while($thread_array[$thread_array_key]->isRunning()) 
  31.           { 
  32.               usleep(10); 
  33.           } 
  34.           if($thread_array[$thread_array_key]->join()) 
  35.           { 
  36.               $variable_data[$thread_array_key] = $thread_array[$thread_array_key]->data; 
  37.           } 
  38.       } 
  39.       return $variable_data
  40.   } 
  41.  
  42.   function model_http_curl_get($url,$userAgent="")  
  43.   { 
  44.       $userAgent = $userAgent ? $userAgent : 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2)';  
  45.       $curl = curl_init(); 
  46.       curl_setopt($curl, CURLOPT_URL, $url); 
  47.       curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); 
  48.       curl_setopt($curl, CURLOPT_TIMEOUT, 5); 
  49.       curl_setopt($curl, CURLOPT_USERAGENT, (www.phpfensi.com)$userAgent); 
  50.       $result = curl_exec($curl); 
  51.       curl_close($curl); 
  52.       return $result
  53.   } 
  54.  
  55.   for ($i=0; $i < 100; $i++)  
  56.   {  
  57.       $urls_array[] = array("name" => "baidu""url" => "http://www.phpfensi.com/s?wd=".mt_rand(10000,20000)); 
  58.   } 
  59.  
  60.   $t = microtime(true); 
  61.   $result = model_thread_result_get($urls_array); 
  62.   $e = microtime(true); 
  63.   echo "多线程:".($e-$t)."\n"
  64.  
  65.   $t = microtime(true); 
  66.   foreach ($urls_array as $key => $value)  
  67.   { 
  68.       $result_new[$key] = model_http_curl_get($value["url"]); 
  69.   } 
  70.   $e = microtime(true); 
  71.   echo "For循环:".($e-$t)."\n"
  72. ?> 

PHP多线程类,代码如下:

  1. /** 
  2.  * @title:  PHP多线程类(Thread) 
  3.  * @version: 1.0 
  4.  * @author:   < web@ > 
  5.  * @published: 2010-11-2 
  6.  *  
  7.  * PHP多线程应用示例: 
  8.  *  require_once 'thread.class.php'; 
  9.  *  $thread = new thread(); 
  10.  *  $thread->addthread('action_log','a'); 
  11.  *  $thread->addthread('action_log','b'); 
  12.  *  $thread->addthread('action_log','c'); 
  13.  *  $thread->runthread(); 
  14.  *   
  15.  *  function action_log($info) { 
  16.  *   $log = 'log/' . microtime() . '.log'; 
  17.  *   $txt = $info . "rnrn" . 'Set in ' . Date('h:i:s', time()) . (double)microtime() . "rn"; 
  18.  *   $fp = fopen($log, 'w'); 
  19.  *   fwrite($fp, $txt); 
  20.  *   fclose($fp); 
  21.  *  } 
  22.  */ 
  23. class thread { 
  24.  
  25.     var $hooks = array(); 
  26.     var $args = array(); 
  27.      
  28.     function thread() { 
  29.     } 
  30.      
  31.     function addthread($func
  32.     { 
  33.      $args = array_slice(func_get_args(), 1); 
  34.      $this->hooks[] = $func
  35.   $this->args[] = $args
  36.   return true; 
  37.     } 
  38.      
  39.     function runthread() 
  40.     { 
  41.      if(isset($_GET['flag'])) 
  42.      { 
  43.       $flag = intval($_GET['flag']); 
  44.      } 
  45.      if($flag || $flag === 0) 
  46.   { 
  47.    call_user_func_array($this->hooks[$flag], $this->args[$flag]); 
  48.   } 
  49.      else  
  50.      { 
  51.          for($i = 0, $size = count($this->hooks); $i < $size$i++) 
  52.          { 
  53.           $fp=fsockopen($_SERVER['HTTP_HOST'],$_SERVER['SERVER_PORT']); 
  54.           if($fp
  55.           { 
  56.            $out = "GET {$_SERVER['PHP_SELF']}?flag=$i HTTP/1.1rn"
  57.            $out .= "Host: {$_SERVER['HTTP_HOST']}rn"
  58.            $out .= "Connection: Closernrn"
  59.                  fputs($fp,$out); 
  60.                  fclose($fp); 
  61.           } 
  62.          } 
  63.      } 
  64.     } 

使用方法,代码如下:

  1. $thread = new thread(); 
  2. $thread->addthread('func1','info1'); 
  3. $thread->addthread('func2','info2'); 
  4. $thread->addthread('func3','info3'); 
  5. $thread->runthread(); 

说明:addthread是添加线程函数,第一个参数是函数名,之后的参数(可选)为传递给指定函数的参数.

runthread是执行线程的函数.

在linux系统中需要配置安装一下pthreads

1、扩展的编译安装(Linux),www.phpfensi.com 编辑参数 --enable-maintainer-zts 是必选项,代码如下:

  1. cd /Data/tgz/php-5.5.1 
  2. ./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 
  3. make clean 
  4. make 
  5. make install        
  6.  
  7. unzip pthreads-master.zip 
  8. cd pthreads-master 
  9. /Data/apps/php/bin/phpize 
  10. ./configure --with-php-config=/Data/apps/php/bin/php-config 
  11. make 
  12. make install 
  13. vi /Data/apps/php/etc/php.ini 

添加如下代码:

extension = "pthreads.so" 

PHP扩展下载:https://github.com/krakjoe/pthreads

PHP手册文档:http://php.net/manual/zh/book.pthreads.php

分享到:
php利用CURL函数登入163邮箱并获取自己的...
php利用CURL函数登入163邮箱并获取自己的通讯录 我们使用phpmailer登录邮件发邮件也是使用了curl原理来实现模仿用户(www.phpfensi.com)发邮件了,今天看了两个利用CURL函数登入163邮箱并获取自己的通讯录的例子. 学习了一些CURL的基础知识并做了这个示例,关于CURL的知识可以从php的官网上查...
PHPMailer发送邮件”SMTP 错误:无法连接...
PHPMailer发送邮件”SMTP 错误:无法连接到 SMTP 主机“ PHPMailer是一个邮件发送插件有很多朋友使用它来发邮件,但也有不少朋友在使用期PHPMailer发邮件时就碰到”SMTP 错误:无法连接到 SMTP 主机“错(www.phpfensi.com)误了,出现这种问题我们从几个点来分享,一个是邮箱配置有问题,另一个是...
  •         php迷,一个php技术的分享社区,专属您自己的技术摘抄本、收藏夹。
  • 在这里……