這篇文章主要介紹了PHP使用Pthread實(shí)現(xiàn)的多線程操作的方法,以完整實(shí)例形式分析了php多線程的創(chuàng)建及使用相關(guān)技巧,需要的朋友可以參考下
本文實(shí)例講述了PHP使用Pthread實(shí)現(xiàn)的多線程操作。分享給大家供大家參考,具體如下:
- <?php
- class vote extends Thread {
- public $res = '';
- public $url = array();
- public $name = '';
- public $runing = false;
- public $lc = false;
- public function __construct($name) {
- $this->res = '暫無,第一次運(yùn)行.';
- $this->param = 0;
- $this->lurl = 0;
- $this->name = $name;
- $this->runing = true;
- $this->lc = false;
- }
- public function run() {
- while ($this->runing) {
- if ($this->param != 0) {
- $nt = rand(1, 10);
- echo "線程[{$this->name}]收到任務(wù)參數(shù)::{$this->param},需要{$nt}秒處理數(shù)據(jù)./n";
- $this->res = rand(100, 999);
- sleep($nt);
- $this->lurl = $this->param;
- $this->param = '';
- } else {
- echo "線程[{$this->name}]等待任務(wù)../n";
- }
- sleep(1);
- }
- }
- }
- //這里創(chuàng)建線程池.
- $pool[] = new vote('a');
- $pool[] = new vote('b');
- $pool[] = new vote('c');
- //啟動所有線程,使其處于工作狀態(tài)
- foreach ($pool as $w) {
- $w->start();
- }
- //派發(fā)任務(wù)給線程
- for ($i = 1; $i < 10; $i++) {
- $worker_content = rand(10, 99);
- while (true) {
- foreach ($pool as $worker) {
- //參數(shù)為空則說明線程空閑
- if ($worker->param=='') {
- $worker->param = $worker_content;
- echo "[{$worker->name}]線程空閑,放入?yún)?shù){$worker_content},上次參數(shù)[{$worker->lurl}]結(jié)果[{$worker->res}]./n";
- break 2;
- }
- }
- sleep(1);
- }
- }
- echo "所有線程派發(fā)完畢,等待執(zhí)行完成./n";
- //等待所有線程運(yùn)行結(jié)束
- while (count($pool)) {
- //遍歷檢查線程組運(yùn)行結(jié)束
- foreach ($pool as $key => $threads) {
- if ($worker->param=='') {
- echo "[{$threads->name}]線程空閑,上次參數(shù)[{$threads->lurl}]結(jié)果[{$threads->res}]./n";
- echo "[{$threads->name}]線程運(yùn)行完成,退出./n";
- //設(shè)置結(jié)束標(biāo)志
- $threads->runing = false;
- unset($pool[$key]);
- }
- }
- echo "等待中.../n";
- sleep(1);
- }
- echo "所有線程執(zhí)行完畢./n";
希望本文所述對大家php程序設(shè)計有所幫助。
新聞熱點(diǎn)
疑難解答