当前位置:首页 > PHP教程 > php高级应用 > 列表

PHP使用Pthread实现的多线程操作实例

发布:smiling 来源: PHP粉丝网  添加日期:2021-06-26 15:38:05 浏览: 评论:0 

这篇文章主要介绍了PHP使用Pthread实现的多线程操作的方法,以完整实例形式分析了php多线程的创建及使用相关技巧,需要的朋友可以参考下,本文实例讲述了PHP使用Pthread实现的多线程操作,分享给大家供大家参考,具体如下:

  1. <?php  
  2. class vote extends Thread { 
  3.   public $res  = ''; 
  4.   public $url  = array(); 
  5.   public $name  = ''; 
  6.   public $runing = false; 
  7.   public $lc   = false; 
  8.   public function __construct($name) { 
  9.     $this->res  = '暂无,第一次运行.'; 
  10.     $this->param  = 0; 
  11.     $this->lurl  = 0; 
  12.     $this->name  = $name; 
  13.     $this->runing = true; 
  14.     $this->lc   = false; 
  15.   } 
  16.   public function run() { 
  17.     while ($this->runing) { 
  18.       if ($this->param != 0) { 
  19.         $nt     = rand(1, 10); 
  20.         echo "线程[{$this->name}]收到任务参数::{$this->param},需要{$nt}秒处理数据.\n"; 
  21.         $this->res  = rand(100, 999); 
  22.         sleep($nt); 
  23.         $this->lurl = $this->param; 
  24.         $this->param  = ''; 
  25.       } else { 
  26.         echo "线程[{$this->name}]等待任务..\n"; 
  27.       } 
  28.       sleep(1); 
  29.     } 
  30.   } 
  31. } 
  32. //这里创建线程池. 
  33. $pool[] = new vote('a'); 
  34. $pool[] = new vote('b'); 
  35. $pool[] = new vote('c'); 
  36. //启动所有线程,使其处于工作状态 
  37. foreach ($pool as $w) { 
  38.   $w->start(); 
  39. } 
  40. //派发任务给线程 
  41. for ($i = 1; $i < 10; $i++) { 
  42.   $worker_content = rand(10, 99); 
  43.   while (true) { 
  44.     foreach ($pool as $worker) { 
  45.       //参数为空则说明线程空闲 
  46.       if ($worker->param=='') { 
  47.         $worker->param = $worker_content; 
  48.         echo "[{$worker->name}]线程空闲,放入参数{$worker_content},上次参数[{$worker->lurl}]结果[{$worker->res}].\n"; 
  49.         break 2; 
  50.       } 
  51.     } 
  52.     sleep(1); 
  53.   } 
  54. } 
  55. echo "所有线程派发完毕,等待执行完成.\n"; 
  56. //等待所有线程运行结束 
  57. while (count($pool)) { 
  58.   //遍历检查线程组运行结束 
  59.   foreach ($pool as $key => $threads) { 
  60.     if ($worker->param=='') { 
  61.       echo "[{$threads->name}]线程空闲,上次参数[{$threads->lurl}]结果[{$threads->res}].\n"; 
  62.       echo "[{$threads->name}]线程运行完成,退出.\n"; 
  63.       //设置结束标志 
  64.       $threads->runing = false; 
  65.       unset($pool[$key]); 
  66.     } 
  67.   } 
  68.   echo "等待中...\n"; 
  69.   sleep(1); 
  70. } 
  71. echo "所有线程执行完毕.\n"; 

希望本文所述对大家php程序设计有所帮助。

Tags: Pthread PHP多线程

分享到: