PHP 初试多线程pthreads扩展

pthread是unix-like多线程支持库,这里能够做为php的多线程扩展支持库。php

我下载的是php_pthreads-2.0.10-5.3-ts-vc9-x86.zip,电脑是64bit,也就是说pthreads在64bit系统上兼容32bit,此版本支持php5.3.x线程安全(ts)版本,固然也名称标注了5.3-ts版本。html

 

注意:下载x64位版本加载不成功的同窗,能够打开apache的log看看是什么问题,若是问题不清楚,不妨下载x86版本的试试也行啊apache

 

在这里安装方式请参阅编程

PHP安装pthreads多线程扩展教程安全

学习请参考自带的Sample或者参考 多线程

PHP 高级编程之多线程学习

 

注意:不要安装太新的版本,不然有可能安装不成功,必定要和php的版本匹配。测试

 

来段代码测试一下:this

<?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";
 }


?>


运行结果.net

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

相关文章
相关标签/搜索