Talk about PHP multi-threaded applications, such as PHP's Pthreads

Source: Internet
Author: User
Let's talk a little bit about PHP multi-threading applications, such as PHP pthreads, which business operations require multithreading?

Reply content:

Let's talk a little bit about PHP multi-threading applications, such as PHP pthreads, which business operations require multithreading?

Http://pecl.php.net/package/pthreads
Download the TGZ package, which provides a number of examples sample code, the simplest is to open multiple threads to capture network resources:


  
   url = $url;    }    public function run() {        // 线程处理一个耗时5秒的任务        for($i=0;$i<5;$i++) {            echo '线程: '.date('H:i:s')."\n";            sleep(1);        }        $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";        sleep(1);    }    // 同步线程并输出线程返回的数据    $request->join();    echo '线程返回数据: '.$request->data[0];}/*如果顺序执行,合计时间将是15秒,借助线程,则只需10秒.生成文件: echo 'Hello' > hello.html运行计时: time php req.php 查看线程: ps -efL|head -n1 && ps -efL|grep php*/

It is important to note that you do not use the echo output in the thread, otherwise unpredictable errors and behavior, such as garbled (garbled), can occur. Especially in non-CLI environments, such as APACHE/PHP-FPM.

PHP don't talk about multithreading, haha

I would also like to know ......... .......

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.