php多线程类的代码分享

php中文网
发布: 2016-07-25 08:57:25
原创
947人浏览过
本文介绍下,有关php中实现多线程的一个类,有需要的朋友参考下。

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

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

代码:

<?php
/**
 * @title:  PHP多线程类(Thread)
 * @version: 1.0
 * @edit by bbs.it-home.org
 * @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);
          }
         }
     }
    }
}
?>
登录后复制

调用示例:

代码小浣熊
代码小浣熊

代码小浣熊是基于商汤大语言模型的软件智能研发助手,覆盖软件需求分析、架构设计、代码编写、软件测试等环节

代码小浣熊 51
查看详情 代码小浣熊
<?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怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号