PHP多線程的實現(PHP多線程類)

經過WEB服務器來實現PHP多線程功能。php

固然,對多線程有深刻理解的人都知道經過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 . "\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);
                }
            }
        }
    }
}

 

使用方法:多線程

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

說明:ui

addthread是添加線程函數,第一個參數是函數名,以後的參數(可選)爲傳遞給指定函數的參數。this

runthread是執行線程的函數。spa

相關文章
相關標籤/搜索