php多任务程序实例解析

yipeiwu_com5年前PHP代码库

本文以实例简单解析了php多任务程序的实现方法,具体代码如下:

<?php
error_reporting(E_ALL);
set_time_limit(0);
/**
* php多任务程序的实现
* 借助proc_open
* 其实该叫进程(process)
* 能启动多进程,你可以使用你的想象力做你想做的了,以后再写个能用的
* 如果你是在linux上跑php,并且启用pcntl模块后,使用pcntl函数该更好
* 
*/
class Thread {
  protected $_pref; // process reference
  protected static $_instance = null;
  protected $_pipes;
  
  private function __construct() {
    $this->_pref = 0;
  }
  
  public static function getInstance($file) {
    if (null == self::$_instance) {
      self::$_instance = new self;
    }
    
    $descriptor = array(
    0 => array("pipe", "r"),
    1 => array("pipe", "w"),
    2 => array("file", "./error-output.txt", "a"),
    );
    self::$_instance->_pref = proc_open("php -q $file", $descriptor, self::$_instance->_pipes);
    return true;
  }
  
  public function __destruct() {
    proc_close($this->_pref);
    $this->_pref = null;
  }
}
// 测试代码
$file = __FILE__;
if(empty($argv[1])) {
  $t2 = Thread::getInstance("$file 1");
  $t3 = Thread::getInstance("$file 2");
  $t4 = Thread::getInstance("$file 3");
  $t5 = Thread::getInstance("$file 4");
  $t5 = Thread::getInstance("$file 5");
  $t5 = Thread::getInstance("$file 6");
  $t2 = Thread::getInstance("$file 7");
  $t3 = Thread::getInstance("$file 8");
  $t4 = Thread::getInstance("$file 9");
  $t5 = Thread::getInstance("$file 10");
  $t5 = Thread::getInstance("$file 11");
  $t5 = Thread::getInstance("$file 12");
  echo "Main thread done\n";
} else {
  $somecontent = "\r\n//~~~~~~~~~~~~-这次请求序号是:" . $argv[1];
  sleep(mt_rand(0, 3));
  $handle = fopen($file, 'a+');
  fwrite($handle, $somecontent);
}

相关文章

php中关于长度计算容易混淆的问题分析

本文实例讲述了php中关于长度计算容易混淆的问题。分享给大家供大家参考,具体如下: 经常被php中数组和字符串的字符函数搞晕,下面总结一下: strlen($string)函数:计算字符...

推荐学习php sesson的朋友必看PHP会话(Session)使用入门第1/2页

 由于 Session 是以文本文件形式存储在服务器端的,所以不怕客户端修改 Session 内容。实际上在服务器端的 Ses...

php 浮点数比较方法详解

浮点数运算精度问题 首先看一个例子: <?php $a = 0.1; $b = 0.9; $c = 1; var_dump(($a+$b)==$c); var_dump...

PHP测试成功的邮件发送案例

mail()函数的作用:连接到邮件服务器,利用smtp协议,与该服务器交互并投邮件。 注意: 1、mail函数不支持esmtp协议,---即,只能直投,不能登陆 2、由上条,我们只能直投...

php实现批量删除挂马文件及批量替换页面内容完整实例

本文实例讲述了php实现批量删除挂马文件及批量替换页面内容的方法。分享给大家供大家参考,具体如下: <?php # functionality: 本程序可以扫描指...