ZTS (Zend Thread Safety) 是 PHP 的執行緒安全版本,用於多執行緒 SAPI (如 Apache worker MPM、IIS)。預設編譯為非執行緒安全 (NTS),用於 PHP-FPM、CLI。pthreads 擴展**強制要求 ZTS 版本 PHP**。
# 下載源碼
cd /usr/local/src
wget https://www.php.net/distributions/php-8.2.10.tar.gz
tar xzf php-8.2.10.tar.gz
cd php-8.2.10
# 關鍵:--enable-maintainer-zts (舊版 --with-tsrm-pthreads)
./configure \
--prefix=/usr/local/php-zts \
--enable-maintainer-zts \
--with-config-file-path=/usr/local/php-zts/etc \
--enable-mbstring \
--with-curl \
--with-openssl \
--with-pdo-mysql=mysqlnd \
--with-mysqli=mysqlnd \
--enable-fpm \
--with-fpm-user=www \
--with-fpm-group=www \
# 其他所需擴展...
make -j$(nproc)
make install
# 驗證
/usr/local/php-zts/bin/php -v | grep -i thread
# 輸出應包含: Zend Thread Safety (ZTS) => enabled
# 使用 ZTS 版本的 phpize/php-config
cd /usr/local/src
wget https://pecl.php.net/get/pthreads-4.1.4.tgz # PHP 8.x 對應版本
tar xzf pthreads-4.1.4.tgz
cd pthreads-4.1.4
/usr/local/php-zts/bin/phpize
./configure --with-php-config=/usr/local/php-zts/bin/php-config
make -j$(nproc)
make install
# 啟用擴展
echo "extension=pthreads" > /usr/local/php-zts/etc/conf.d/pthreads.ini
/usr/local/php-zts/bin/php -m | grep pthreads
# 應輸出 pthreads
/usr/local/php-zts/bin/php -r "
\$t = new class extends Thread {
public function run() { echo \"Thread running\n\"; }
};
\$t->start();
\$t->join();
"
| 錯誤 | 原因 | 解決 |
|---|---|---|
configure: error: pthreads requires ZTS | PHP 非 ZTS 編譯 | 重新編譯 PHP 加 --enable-maintainer-zts |
phpize: command not found | 未安裝 php-dev / php-devel | apt install php8.2-dev 或 yum install php-devel |
No configure script found | 下載的是 GitHub 源碼非 PECL 發布包 | 必須從 pecl.php.net/get/pthreads- 下載 |
編譯通過但啟動報 undefined symbol | PHP 版本與 pthreads 版本不匹配 | 嚴格對應:PHP 8.0/8.1→pthreads 4.x, PHP 7.x→pthreads 3.x |
Fiber 類原生支援協程式並發,無需 ZTS、無需擴展。<?php
$fiber = new Fiber(function (): void {
$value = Fiber::suspend('fiber suspended');
echo "Fiber resumed with: $value\n";
});
$value = $fiber->start();
echo "Main: $value\n";
$fiber->resume('main resumed');
echo "Done\n";
若維護舊專案必須用 pthreads,嚴格按上述流程編譯 ZTS PHP + 對應版本 pthreads。新專案請直接使用 PHP 8.1+ Fibers 或 Swoole/OpenSwoole,獲得更好效能、更簡單部署、官方長期支援。