教程集 www.jiaochengji.com
教程集 >  脚本编程  >  php  >  正文 php多线程类的代码分享

php多线程类的代码分享

发布时间:2016-09-15   编辑:jiaochengji.com
本文介绍下,有关php中实现多线程的一个类,有需要的朋友参考下。

如何通过WEB服务器实现PHP的多线程功能呢?
在php编程中,通过WEB服务器实现的多线程只能模仿多线程的一些效果,并不是真正意义上的多线程。

在需要类似多线程的功能时,可以参考下下面的这个类。

代码:

<?php
/**
 * @title:  PHP多线程类(Thread)
 * @version: 1.0
 * @edit by www.jbxue.com
 * @published: 2013/7/18
 * 
 * PHP多线程应用示例:
 *  require_once 'thread.class.php';
 *  $thread = new thread();
 *  $thread->addthread('action_log','a');
 *  $thread->addthread('action_log','b');
 *  $thread->addthread('action_log','c');
 *  $thread->runthread();
 *  
 *  function action_log($info) {
 *   $log = 'log/' . microtime() . '.log';
 *   $txt = $info . "\r\n\r\n" . 'Set in ' . Date('h:i:s', time()) . (double)microtime() . "\r\n";
 *   $fp = fopen($log, 'w');
 *   fwrite($fp, $txt);
 *   fclose($fp);
 *  }
 */
class thread {
    var $hooks = array();
    var $args = array();    
    function thread() {
    }
    
    function addthread($func)
    {
     $args = array_slice(func_get_args(), 1);
     $this->hooks[] = $func;
  $this->args[] = $args;
  return true;
    }
    
    function runthread()
    {
     if(isset($_GET['flag']))
     {
      $flag = intval($_GET['flag']);
     }
     if($flag || $flag === 0)
  {
   call_user_func_array($this->hooks[$flag], $this->args[$flag]);
  }
     else 
     {
         for($i = 0, $size = count($this->hooks); $i < $size; $i++)
         {
          $fp=fsockopen($_SERVER['HTTP_HOST'],$_SERVER['SERVER_PORT']);
          if($fp)
          {
           $out = "GET {$_SERVER['PHP_SELF']}?flag=$i HTTP/1.1\r\n";
           $out .= "Host: {$_SERVER['HTTP_HOST']}\r\n";
           $out .= "Connection: Close\r\n\r\n";
                 fputs($fp,$out);
                 fclose($fp);
          }
         }
     }
    }
}
?>

调用示例:

<?php
//多线程调用示例
$thread = new thread();
$thread->addthread('func1','info1');
$thread->addthread('func2','info2');
$thread->addthread('func3','info3');
$thread->runthread();
?>

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

附,下载地址:php多线程类的源码。

您可能感兴趣的文章:
php不支持多线程怎么办
php多线程之管道通信的例子
php多线程类的代码分享
php socket多线程服务器的实例分享
php curl 多线程类实例分享
php模拟多线程的实例分享
Java多线程原理及ThreadLocal多线程实例详解
多线程程序设计 (转)
如何编写线程安全的JSP程序
php文件上传代码大全(实例分享)

[关闭]
~ ~