環境需求
- PHP 必須編譯為線程安全(ZTS,
--enable-zts)。
- 建議獨立安裝 ZTS 版本(如
/usr/local/php-zts),避免影響現有環境。
編譯安裝步驟
# 1. 下載 PHP 原始碼並編譯 ZTS 版本
tar zxvf php-5.4.5.tar.gz
cd php-5.4.5
./configure --enable-zts --prefix=/usr/local/php-zts
make && make install
# 2. 安裝 pthreads(以 0.0.45 穩定版為例)
tar zxvf pthreads-0.0.45.tgz
cd pthreads-0.0.45
/usr/local/php-zts/bin/phpize
./configure --with-php-config=/usr/local/php-zts/bin/php-config
make && make install
# 3. 修改 php.ini 載入擴展
echo "extension=pthreads.so" >> /usr/local/php-zts/lib/php.ini
驗證安裝
/usr/local/php-zts/bin/php -m | grep pthreads
# 應輸出 pthreads
核心類別與同步機制
| 類別 | 用途 |
Thread | 執行緒基礎類,繼承並實作 run() |
Worker | 可重用執行緒,堆疊任務 (stack()) |
Pool | Worker 池,管理多個 Worker |
Volatile | 可變動物件容器(線程間共享) |
Collectable | 可回收任務介面 |
Mutex / Cond | 互斥鎖與條件變數,配合 synchronized() 使用 |
入門範例:Thread 基本操作與資料共享
<?php
class TestObject { public $val; }
class Fetching extends Thread {
public function run() {
$this->sym = 10245;
$this->arr = ["1","2","3"];
$obj = new TestObject(); $obj->val = "testval";
$this->obj = $obj;
$this->objs = serialize($obj);
$this->res = fopen("php://stdout", "w");
$this->synchronized(function(){ $this->notify(); }); // 通知主線程資料就緒
$this->synchronized(function(){ $this->wait(); }); // 等待主線程處理完畢
}
}
$thread = new Fetching();
$thread->start();
$thread->synchronized(function($t){
$t->wait(); // 等待子線程 notify
}, $thread);
foreach (["sym","arr","obj","objs","res"] as $sym) {
printf("\$thread->%s: ", $sym);
$val = $thread->$sym;
if ($val) {
if ($sym === "objs") var_dump(unserialize($val));
else var_dump($val);
}
}
$thread->synchronized(function($t){ $t->notify(); }, $thread); // 釋放子線程
?>
執行結果關鍵點
- 主線程與子線程透過
synchronized() + wait()/notify() 協作。
- 物件、陣列、資源皆可跨線程存取(資源需謹慎處理)。
- 序列化物件可跨線程傳遞複雜結構。
遷移提示(pthreads v3+ / PHP 7+)
- PHP 7 僅支援 pthreads v3,API 有變動(如
Threaded 取代部分基礎類)。
- 生產環境建議改用 Swoole 或 OpenSwoole 協程方案,效能更高、生態更完善。
- pthreads 官方已停止維護,僅供舊專案維護參考。