我們在之前給大家介紹了php多線程的實現方法,以及非同步呼叫,都知道通過WEB伺服器實現的多線程只能模仿多線程的一些效果,並不是真正意義上的多線程.但不管怎麼樣,它還是能滿足我們的一些需要的,那麼今天我們就實現php多線程的類!
php多線程類:
/** * @title: PHP多線程類(Thread) * @version: 1.0 * * 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 . "rnrn" . 'Set in ' . Date('h:i:s', time()) . (double)microtime() . "rn"; * $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.1rn"; $out .= "Host: {$_SERVER['HTTP_HOST']}rn"; $out .= "Connection: Closernrn"; fputs($fp,$out); fclose($fp); } } } } }
使用方法,代碼如下:
$thread = new thread(); $thread->addthread('func1','info1'); $thread->addthread('func2','info2'); $thread->addthread('func3','info3'); $thread->runthread();
說明:
addthread() 是添加線程函數,第一個參數是函數名,之後的參數(可選)為傳遞給指定函數的參數.
runthread() 是執行線程的函數.
總結:
本文給大家分享了一個php多線程的類,以後就不需要在去寫那麼多代碼,下次需要的時候就可以直接調用了,希望可以對你有所協助!
相關推薦:
php實現非同步呼叫多線程的方法
php多線程類比實現的三種方法介紹
php多線程的實現執行個體
php多線程一種實現方法—shell