Rumah > pembangunan bahagian belakang > tutorial php > php多线程的创建及使用

php多线程的创建及使用

墨辰丷
Lepaskan: 2023-03-29 22:08:01
asal
2430 orang telah melayarinya

本篇文章主要介绍php多线程的创建及使用,感兴趣的朋友参考下,希望对大家有所帮助。

实例讲述了PHP使用Pthread实现的多线程操作。分享给大家供大家参考,具体如下:


<?php 
class vote extends Thread {
  public $res  = &#39;&#39;;
  public $url  = array();
  public $name  = &#39;&#39;;
  public $runing = false;
  public $lc   = false;
  public function __construct($name) {
    $this->res  = &#39;暂无,第一次运行.&#39;;
    $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  = &#39;&#39;;
      } else {
        echo "线程[{$this->name}]等待任务..\n";
      }
      sleep(1);
    }
  }
}
//这里创建线程池.
$pool[] = new vote(&#39;a&#39;);
$pool[] = new vote(&#39;b&#39;);
$pool[] = new vote(&#39;c&#39;);
//启动所有线程,使其处于工作状态
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==&#39;&#39;) {
        $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==&#39;&#39;) {
      echo "[{$threads->name}]线程空闲,上次参数[{$threads->lurl}]结果[{$threads->res}].\n";
      echo "[{$threads->name}]线程运行完成,退出.\n";
      //设置结束标志
      $threads->runing = false;
      unset($pool[$key]);
    }
  }
  echo "等待中...\n";
  sleep(1);
}
echo "所有线程执行完毕.\n";
Salin selepas log masuk



总结:以上就是本篇文的全部内容,希望能对大家的学习有所帮助。

相关推荐:

PHP中Enum的使用技巧

PHP生成PDF文件的方法

PHP MPDF中文乱码如何解决


Atas ialah kandungan terperinci php多线程的创建及使用. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Artikel terbaru oleh pengarang
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan