php多任务程序实例解析

yipeiwu_com6年前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中动态显示签名和ip原理

<?php  //包含一个计数器,一个提醒语句,用户ip以及自己的广告图片。 //给浏览器发送头,说我是张图片 Header("Content-type: im...

php删除文本文件中重复行的方法

本文实例讲述了php删除文本文件中重复行的方法。分享给大家供大家参考。具体分析如下: 这个php函数用来删除文件中的重复行,还可以指定是否忽略大小写,和指定换行符 /** * Re...

Erlang的运算符(比较运算符,数值运算符,移位运算符,逻辑运算符)

Erlang的比较运算符 opDescription==等于/=不等于=<小于等于<小于>=大于等于>大于=:=精确的等于=/=精确的不等于等于和精确等于的区别:...

php记录代码执行时间(实现代码)

复制代码 代码如下:$t1 = microtime(true);// ... 执行代码 ...$t2 = microtime(true);echo '耗时'.round($t2-$t1,...

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 2611816 bytes)

今天要用php代码来处理一个580M的日志文件,总共有219万多行记录,因为是.log的文件,在windows下面很难将文件按照条数来分割,于是在linux下用split -l 1000...