时间:2021-07-01 10:21:17 帮助过:33人阅读
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("www.google.com");
- $chB = new Request("www.baidu.com");
- $chG ->start();
- $chB ->start();
- $chG->join();
- $chB->join();
- $gl = $chG->response;
- $bd = $chB->response;
以上就是php如何实现多线程?的详细内容,更多请关注Gxl网其它相关文章!