pthread是unix-like多线程支持库,这里可以作为php的多线程扩展支持库。
我下载的是php_pthreads-2.0.10-5.3-ts-vc9-x86.zip,电脑是64bit,也就是说pthreads在64bit系统上兼容32bit,此版本支持php5.3.x线程安全(ts)版本,当然也名称标注了5.3-ts版本。
注意:下载x64位版本加载不成功的同学,可以打开apache的log看看是什么问题,如果问题不清楚,不妨下载x86版本的试试也行啊
在这里安装方式请参阅
学习请参考自带的Sample或者参考
注意:不要安装太新的版本,否则有可能安装不成功,一定要和php的版本匹配。
来段代码测试一下:
<?php
error_reporting(E_ALL);
ob_implicit_flush();
header('content-type:text/html;charset=utf-8');
class AsyncTask extends Thread {
private $arg;
private $index;
public function __construct($arg){
$this->arg = $arg;
$this->index = 0;
}
public function run(){
if($this->arg){
while($this->index<5)
{
echo microtime(true)."--".$this->arg."->ID:".(Thread::getCurrentThreadId())."---index=".$this->index."<br/>";
$this->index++;
}
}
}
}
$threadA = new AsyncTask("WokerA");
$threadB = new AsyncTask("WokerB");
if($threadA->start() && $threadB->start())
{
$threadA->join();
$threadB->join();
$index = 0;
while($index<5){
echo "<font color='red'>".microtime(true)."---主线程ID".(Thread::getCurrentThreadId())."--index=".$index."</font><br/>";
$index++;
}
}else{
echo "failed";
}
?>
运行结果
通过时间输出对比,我们发现,主线程和子线程符合多线程运行效果,但对于结果的输出和时间不匹配,可是每个线程都有一个缓冲区吧(I Guess)。
来源:oschina
链接:https://my.oschina.net/u/2256215/blog/651994