1. 程式人生 > >PHP Pthread多執行緒操作

PHP Pthread多執行緒操作

<?php 


class vote extends Thread {


    public $res    = '';
    public $url    = array();
    public $name   = '';
    public $runing = false;
    public $lc     = false;


    public function __construct($name) {


        $this->res    = '暫無,第一次執行.';
        $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}]收到任務引數::{$this->param},需要{$nt}秒處理資料.\n";
                $this->res   = rand(100, 999);
                sleep($nt);
                $this->lurl = $this->param;
                $this->param   = '';
            } else {
                echo "執行緒[{$this->name}]等待任務..\n";
            }
            sleep(1);
        }
    }


}


//這裡建立執行緒池.
$pool[] = new vote('a');
$pool[] = new vote('b');
$pool[] = new vote('c');


//啟動所有執行緒,使其處於工作狀態
foreach ($pool as $w) {
    $w->start();
}


//派發任務給執行緒
for ($i = 1; $i < 10; $i++) {
    $worker_content = rand(10, 99);
    while (true) {
        foreach ($pool as $worker) {
            //引數為空則說明執行緒空閒
            if ($worker->param=='') {
                $worker->param = $worker_content;
                echo "[{$worker->name}]執行緒空閒,放入引數{$worker_content},上次引數[{$worker->lurl}]結果[{$worker->res}].\n";
                break 2;
            }
        }
        sleep(1);
    }
}
echo "所有執行緒派發完畢,等待執行完成.\n";


//等待所有執行緒執行結束
while (count($pool)) {
    //遍歷檢查執行緒組執行結束
    foreach ($pool as $key => $threads) {
        if ($worker->param=='') {
            echo "[{$threads->name}]執行緒空閒,上次引數[{$threads->lurl}]結果[{$threads->res}].\n";
            echo "[{$threads->name}]執行緒執行完成,退出.\n";
            //設定結束標誌
            $threads->runing = false;
            unset($pool[$key]);
        }
    }
    echo "等待中...\n";
    sleep(1);
}
echo "所有執行緒執行完畢.\n";