Home  >  Article  >  Backend Development  >  How to implement multi-threading in php?

How to implement multi-threading in php?

(*-*)浩
(*-*)浩Original
2019-09-27 11:46:532111browse

How to implement multi-threading in php?

How to implement multi-threading in PHP: (Recommended learning: PHP programming from entry to proficiency)

Use the shell_exech function in shell mode. Each time you add a thread, it is equivalent to using PHP to open a shell for independent operations.

Add Pthread to your PHP Extension, and then use the API provided by Pthread to operate PHP multi-threading.

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

The following is a thread class used to request a certain interface. Next, write two multi-threaded application examples based on it:

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);
    }
}

Asynchronous request

Split the synchronous request into multiple threads for asynchronous calls, To improve the operating efficiency of the program.

$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;

The above is the detailed content of How to implement multi-threading in php?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn