php pthread扩展,PHP 初试多线程pthreads扩展

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的版本匹配。

来段代码测试一下:

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."
";

$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 "".microtime(true)."---主线程ID".(Thread::getCurrentThreadId())."--index=".$index."
";

$index++;

}

}else{

echo "failed";

}

?>

运行结果

0818b9ca8b590ca3270a3433284dd417.png

通过时间输出对比,我们发现,主线程和子线程符合多线程运行效果,但对于结果的输出和时间不匹配,可是每个线程都有一个缓冲区吧(I Guess)。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值