php多线程之pthread示例

//测试扩展pthreads是否安装成功
class AsyncOperation extends Thread {  
  public function __construct($arg){  
    $this->arg = $arg;  
  }  
  
  public function run(){  
    if($this->arg){  
      printf("Hello %s\n", $this->arg);  
    }  
  }  
}  
$thread = new AsyncOperation("World");  
if($thread->start())  
  $thread->join();  
  
exit;

 

//pthreads使用
// Threaded implements Traversable , Countable , ArrayAccess 

//初始化对象
$safe = new Threaded();
//通过ArrayAccess接口添加10个属性
while (count($safe) < 10) {
    $safe[] = count($safe);
}
var_dump($safe);
//通过Countable接口获取属性个数
var_dump(count($safe));
//提取前五个属性
var_dump($safe->chunk(5,1));
var_dump(count($safe));
//通过Traversable接口轮询剩下的属性
foreach($safe as $val){
	var_dump($val);
}
var_dump(count($safe));

 

class My extends Thread {
    public function run() {
			echo 1;
			//这里退出了就终止了,才有终止信息返回
        //@not_found();
			echo 1;exit;
    }
}

$my = new My();
$my->start();
$my->join();

var_dump($my->isTerminated(), $my->getTerminationInfo());

 

class vote extends Thread {

    public $res    = '';
    public $url    = array();
    public $name   = '';
    public $runing = false;
    public $lc     = false;

    public function __construct($name) {

        $this->res    = '暂无,第一次运行.';
        $this->param    = 0;
        $this->lurl   = 0;
        $this->name   = $name;
        $this->runing = true;
        $this->lc     = false;
    }

    public function run() {
        while ($this->runing) {

            if ($this->param != 0) {
                $nt          = rand(1, 10);
                echo "线程[{$this->name}]收到任务参数::{$this->param},需要{$nt}秒处理数据.\n";
                $this->res   = rand(100, 999);
                sleep($nt);
                $this->lurl = $this->param;
                $this->param   = '';
            } else {
                echo "线程[{$this->name}]等待任务..\n";
            }
            sleep(1);
        }
    }

}

//这里创建线程池.
$pool[] = new vote('a');
$pool[] = new vote('b');
$pool[] = new vote('c');

//启动所有线程,使其处于工作状态
foreach ($pool as $w) {
    $w->start();
}

//派发任务给线程
for ($i = 1; $i < 10; $i++) {
    $worker_content = rand(10, 99);
    while (true) {
        foreach ($pool as $worker) {
            //参数为空则说明线程空闲
            if ($worker->param=='') {
                $worker->param = $worker_content;
                echo "[{$worker->name}]线程空闲,放入参数{$worker_content},上次参数[{$worker->lurl}]结果[{$worker->res}].\n";
                break 2;
            }
        }
        sleep(1);
    }
}
echo "所有线程派发完毕,等待执行完成.\n";

//等待所有线程运行结束
while (count($pool)) {
    //遍历检查线程组运行结束
    foreach ($pool as $key => $threads) {
        if ($worker->param=='') {
            echo "[{$threads->name}]线程空闲,上次参数[{$threads->lurl}]结果[{$threads->res}].\n";
            echo "[{$threads->name}]线程运行完成,退出.\n";
            //设置结束标志
            $threads->runing = false;
            unset($pool[$key]);
        }
    }
    echo "等待中...\n";
    sleep(1);
}
echo "所有线程执行完毕.\n";

 

//通过Stackable共享线程数据
class data extends Stackable{
    //private $name;
    public function __construct($_name) {
        //$this->name = $_name;//if you set any variable, workers will get the variable, so do not set any variable
        echo __FILE__.'-'.__LINE__.'<br/>'.chr(10);
    }
    public function run(){
        echo __FILE__.'-'.__LINE__.'<br/>'.chr(10);
    }
}
class readWorker extends Worker {
    public function __construct(&$_data) {
        $this->data = $_data;//
    }
    public function run(){
        while(1){
            if($arr=$this->data->shift())//receiving datas
            {
                echo 'Received data:'.print_r($arr,1).chr(10);
            }else usleep(50000);
        }
    }
}
class writeWorker extends Worker {
    public function __construct(&$_data) {
        $this->data = $_data;//
    }
    public function run(){
        while(1){
            $this->data[] = array(time(),rand());//writting datas
            usleep(rand(50000, 1000000));
        }
    }

}
$data = new data('');
$reader = new readWorker($data);
$writer = new writeWorker($data);
$reader->start();
$writer->start();

 

class storage extends Stackable {
public function run(){}
}

class my extends Thread {
public function __construct($storage) {
$this->storage = $storage;
}

public function run(){
$i = 0;
while(++$i < 10) {
$this->storage[]=rand(0,1000);
}

$this->synchronized(function($thread){
$thread->notify();
}, $this);
}
}

$storage = new storage();
$my = new my($storage);
$my->start();

$my->synchronized(function($thread){
$thread->wait();
}, $my);

var_dump($storage);
exit;

 

class test_thread_run extends Thread   
  {  
      public $url;  
      public $data;  
  
      public function __construct($url)  
      {  
          $this->url = $url;  
      }  
  
      public function run()  
      {  
          if(($url = $this->url))  
          {  
              $this->data = model_http_curl_get($url);  
          }  
      }  
  }  
  
  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;  
  }  
  
  function model_http_curl_get($url,$userAgent="")   
  {  
      $userAgent = $userAgent ? $userAgent : 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2)';   
      $curl = curl_init();  
      curl_setopt($curl, CURLOPT_URL, $url);  
      curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);  
      curl_setopt($curl, CURLOPT_TIMEOUT, 5);  
      curl_setopt($curl, CURLOPT_USERAGENT, $userAgent);  
      $result = curl_exec($curl);  
      curl_close($curl);  
      return $result;  
  }  
  //10没有效果,20才有效果
  for ($i=0; $i < 20; $i++)   
  {   
      $urls_array[] = array("name" => "baidu", "url" => "http://www.baidu.com/s?wd=".mt_rand(10000,20000));  
  }  
  
  $t = microtime(true);  
  $result = model_thread_result_get($urls_array);  
  $e = microtime(true);  
  echo "多线程:".($e-$t)."\n";  
  
  $t = microtime(true);  
  foreach ($urls_array as $key => $value)   
  {  
      $result_new[$key] = model_http_curl_get($value["url"]);  
  }  
  $e = microtime(true);  
  echo "For循环:".($e-$t)."\n";  
exit;

 

posted on 2014-04-01 15:18  kudosharry  阅读(383)  评论(0编辑  收藏  举报

导航