Let’s talk about php multithreading applications, such as php pthreads

  ios, question

Let’s talk briefly about php multithreading applications, such as php pthreads, which business operations require multithreading?

Download tgz package, which provides many examples of code, the simplest is to open multiple threads to collect network resources:

class Request extends Thread {
    public $url;
    public $data;
    public function __construct($url) {
        $this->url = $url;
    public function run() {
        // 线程处理一个耗时5秒的任务
        for($i=0;$i<5;$i加加) {
            echo '线程: '.date('H:i:s')."\n";
        $response = file_get_contents($this->url);
        if ($response) {
            $this->data = array($response);
        echo "线程: 任务完成\n";
$request = new Request('hello.html');
// 运行线程:start()方法会触发run()运行
if ($request->start()) {
    // 主进程处理一个耗时10秒的任务,此时线程已经工作
    for($i=0;$i<10;$i加加) {
        echo '进程: '.date('H:i:s')."\n";
    // 同步线程并输出线程返回的数据
    echo '线程返回数据: '.$request->data[0];
生成文件: echo 'Hello' > hello.html
运行计时: time php req.php 
查看线程: ps -efL|head -n1 && ps -efL|grep php

PHP pthreads

It is worth noting that echo output should not be used in thread inside, otherwise unpredictable errors and behaviors, such as garbled, will occur, especially in non-CLI environments, such as Apache/PHP-FPM.