建站学 - 轻松建站从此开始!

建站学-个人建站指南,网页制作,网站设计,网站制作教程

当前位置: 建站学 > 网站开发 > PHP教程 >

通过WEB服务器来实现PHP多线程功能

时间:2012-04-13 15:04来源: 作者: 点击:
当然,对多线程有深入理解的人都知道通过WEB服务器实现的多线程只能模仿多线程的一些效果,并不是真正意义上的多线程。 但不管怎么样,它还是能满足我们的一些需要的,在需要类似多线程的功能方面还是可以采用这个类。     /**     &

当然,对多线程有深入理解的人都知道通过WEB服务器实现的多线程只能模仿多线程的一些效果,并不是真正意义上的多线程。

但不管怎么样,它还是能满足我们的一些需要的,在需要类似多线程的功能方面还是可以采用这个类。

    /**  
     * @title:      PHP多线程类(Thread)  
     * @version:    1.0  
     * @author:     phper.org.cn < web@phper.org.cn >  
     * @published:  2010-11-2  
     *   
     * 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 . " " . 'Set in ' . Date('h:i:s', time()) . (double)microtime() . " ";  
     *      $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 ";   
                        $out .= "Host: {$_SERVER['HTTP_HOST']} ";   
                        $out .= "Connection: Close ";   
                        fputs($fp,$out);   
                        fclose($fp);   
                    }   
                }   
            }   
        }   
    } 

使用方法:

    $thread = new thread();   
    $thread->addthread('func1','info1');   
    $thread->addthread('func2','info2');   
    $thread->addthread('func3','info3');   
    $thread->runthread(); 

说明:

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

runthread是执行线程的函数。 (责任编辑:admin)
织梦二维码生成器
顶一下
(0)
0%
踩一下
(0)
0%
------分隔线----------------------------
发表评论
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
评价:
表情:
用户名: 验证码:点击我更换图片