PHP多線程(pthreads)參數傳遞學習筆記

來源:互聯網
上載者:User

測試環境

OS: win7 64
PHP: 5.4.25 ts
pthreads: 0.1.0


1.效能問題

2.PDO等某些類型不能serialize所以就不能傳遞到線程。
這兩個問題是能通過其他凡是解決的,解決方案仁者見仁智者見智。

另外,可以通過傳遞匿名函數到線程中,但是有個bug,匿名函數不能賦值給線程中的屬性,導致傳遞的匿名函數只能線上程的構造方法中才能使用(call_user_fun*系列函數調用)。

Thread屬性定義一定要注意必須在構造方法中初始化,否則必定為null。__construct()和run()裡面的代碼不在一個次元,如果屬性不是PHP標量在run()中不能修改,例如構造方法中初始化一個對象,然後run()中修改對象屬性不會生效。

正確寫法:

 代碼如下 複製代碼

abstract class Task extends Thread {
 private $finished;
 public $terminated;
 protected $id;
 public $terminate;
 public function __construct($id) {
  $this->id = $id;
  $this->terminated = true;
  $this->finished = false;
  $this->terminate = false;
 }
}

錯誤寫法:

 代碼如下 複製代碼

abstract class Task extends Thread {
 private $finished=false;
 public $terminated=false;
 protected $id;// www.111cn.net
 public $terminate=false;
 public function __construct($id) {
  $this->id = $id;
 }
}


這樣也是錯的,無論stdClass還是數組

 代碼如下 複製代碼
abstract class Task extends Thread {
 private $info;
 public function __construct($task) {
  $this->info = array();
  $this->info ['task'] = $task;
  $this->info ['finished'] = false;
  $this->info ['terminate'] = false;
  $this->info ['terminated'] = false;
  $this->info ['error'] = false;
  $this->info ['info'] = array ();
 }
}


後來研究又發現,複合類型的資料整體賦值貌似能起作用。

如果程式有很多回呼函數線上程內部用的話就是找死啊。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.