PHP使用Pthread實現的多線程操作執行個體_php技巧

來源:互聯網
上載者:User

本文執行個體講述了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";

希望本文所述對大家php程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.