php下 pthread的安装需要重新编译php
以最新的 php5.67为例
wget http://am1.php.net/distributions/php-5.6.7.tar.gz
然后编译
./configure --prefix=/usr/local/php --with-config-file-path=/usr/local/php/etc --with-curl --with-freetype-dir --with-jpeg-dir --with-png-dir --with-gd --enable-gd-native-ttf --with-iconv --with-libxml-dir --with-mhash --with-mcrypt --with-mysql --with-mysqli --with-openssl --with-xmlrpc --with-zlib --disable-debug --disable-rpath --enable-bcmath --enable-fpm --enable-inline-optimization --enable-mbregex --enable-mbstring --enable-pcntl --enable-shmop --enable-soap --enable-sockets --enable-sysvsem --enable-xml --enable-zip --with-libdir=lib64 --without-pear --with-gd --enable-gd-native-ttf --with-openssl --with-mhash --enable-pcntl --enable-sockets --with-xmlrpc --enable-zip --enable-soap --enable-opcache --with-pdo-mysql --enable-maintainer-zts
cp php.ini-production /usr/local/php/etc/php.ini
下载最新版的pthreads
wget https://github.com/krakjoe/pthreads/archive/v2.0.10.tar.gz
1 /usr/local/php/bin/phpize 2 ./configure --with-php-config=/usr/local/php/bin/php-config make && make install /usr/local/php/lib/php/extensions/no-debug-zts-20131226/ extension = pthreads.so
案例
<?php class test_thread_run extends Thread { public $url; public $data; public function __construct($url){ $this->url = $url; } public function run(){ if(($url = $this->url)) { echo 'microtime:'.microtime(); sleep(10); echo $this->url."\r\n"; } } } for ($i=0; $i < 100; $i++){ $urls_array[] = array("name" => "baidu", "url" => "http://www.baidu.com/s?wd=".mt_rand(10000,20000)); } function model_thread_result_get($urls_array){ foreach ($urls_array as $key => $value){ $thread_array[$key] = new test_thread_run($value["url"]); $thread_array[$key]->start(); } foreach ($thread_array as $thread_array_key => $thread_array_value){ while($thread_array[$thread_array_key]->isRunning()){ usleep(10); } if($thread_array[$thread_array_key]->join()){ $variable_data[$thread_array_key] = $thread_array[$thread_array_key]->data; } } return $variable_data; } $result = model_thread_result_get($urls_array); ?>