好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

php如何实现多线程?

PHP实现多线程的方法: (推荐学习:PHP编程从入门到精通)

使用shell_exech函数,以shell的方式,每添加一个线程,就相当于你使用php打开了一个shell进行独立的操作

给你的PHP添加Pthread扩展,然后使用Pthread所提供的API来操作PHP的多线程。

<?php
class pthreadsTest extends Thread {
    public function run () {
   sleep(5);
    }
}
$ts1 = new pthreadsTest();
$ts1->start(); 
$ts2 = new pthreadsTest();
$ts2->start(); 
?>

下面是一个线程类,用来请求某一接口。接下来根据它写两个多线程的应用实例:

class Request extends Thread {
    public $url;
    public $response;
    public function __construct($url) {
   $this->url = $url;
    }
    public function run() {
   $this->response = file_get_contents($this->url);
    }
}

异步请求

将同步的请求拆分为多个线程异步调用,以提升程序的运行效率。

$chG = new Request("HdhCmsTestgoogle测试数据");
$chB = new Request("HdhCmsTestbaidu测试数据");
$chG ->start();
$chB ->start();
$chG->join();
$chB->join();

$gl = $chG->response;
$bd = $chB->response;

以上就是php如何实现多线程?的详细内容,更多请关注Gxl网其它相关文章!

查看更多关于php如何实现多线程?的详细内容...

  阅读:69次

上一篇: php如何实现队列

下一篇:php和js区别