PHP 預設為非線程安全(NTS)模式編譯,若需使用 pthreads 等多線程擴展,必須啟用線程安全(ZTS, Zend Thread Safety)模式重新編譯 PHP。本文詳細記錄 ZTS 模式編譯流程與 pthreads 安裝常見問題解決方案。
cd /usr/local/src
wget https://www.php.net/distributions/php-5.5.12.tar.gz
tar -xzf php-5.5.12.tar.gz
cd php-5.5.12
./configure \
--prefix=/usr/local/php5.5.12-zts \
--enable-maintainer-zts \
--with-config-file-path=/usr/local/php5.5.12-zts/etc \
--enable-fpm \
--with-mysql=mysqlnd \
--with-mysqli=mysqlnd \
--with-pdo-mysql=mysqlnd \
--with-openssl \
--with-curl \
--with-zlib \
--enable-mbstring \
--enable-sockets \
--enable-pcntl
make -j$(nproc)
make install
/usr/local/php5.5.12-zts/bin/php -i | grep "Thread Safety"
# 輸出應為:Thread Safety => enabled
注意:pthreads 版本必須與 PHP 版本嚴格對應。PHP 5.5 對應 pthreads 2.x 系列。
cd /usr/local/src
wget https://pecl.php.net/get/pthreads-2.0.10.tgz # 建議使用 2.0.10 穩定版
tar -xzf pthreads-2.0.10.tgz
cd pthreads-2.0.10
原始碼包不包含 configure 腳本,必須使用 PHP 安裝目錄下的 phpize 生成:
/usr/local/php5.5.12-zts/bin/phpize
執行成功後,目錄下將出現 configure 等配置文件。
./configure --with-php-config=/usr/local/php5.5.12-zts/bin/php-config
make -j$(nproc)
make install
編輯 php.ini,添加:
extension=pthreads.so
/usr/local/php5.5.12-zts/bin/php -m | grep pthreads
# 應輸出 pthreads
原因:PECL 擴展原始碼包不含 configure,需先執行 phpize。
解決:確保使用 ZTS 版本 PHP 的 phpize 路徑:
/usr/local/php5.5.12-zts/bin/phpize
原因:當前 PHP 非線程安全模式。
解決:重新編譯 PHP 並添加 --enable-maintainer-zts 參數。
對照表:
| PHP 版本 | pthreads 版本 |
|---|---|
| 5.3 | 0.x / 1.x |
| 5.4 - 5.6 | 2.x |
| 7.0 - 7.4 | 3.x |
| 8.0+ | 不再支援,建議使用 Fiber / Swoole |
PHP 7.4+ 官方已移除 pthreads 支援,生產環境建議遷移至:
PHP ZTS 編譯與 pthreads 安裝的核心在於:PHP 必須以 --enable-maintainer-zts 編譯,且 pthreads 版本必須與 PHP 版本嚴格對應。安裝時務必使用 ZTS 版本的 phpize 和 php-config。現代專案建議採用 Swoole 或 Fiber 等更先進的並發方案。