Home  >  Article  >  Backend Development  >  聊一下php多线程的应用场合吧,例如php的pthreads

聊一下php多线程的应用场合吧,例如php的pthreads

WBOY
WBOYOriginal
2016-06-06 20:36:491116browse

大家简单聊一下php多线程的应用场合吧,例如php的pthreads,哪些业务操作需要用多线程?

回复内容:

大家简单聊一下php多线程的应用场合吧,例如php的pthreads,哪些业务操作需要用多线程?

http://pecl.php.net/package/pthreads
下载tgz包,里面提供有众多examples示例代码,最简单的就是开启多个线程采集网络资源:

<code><?php class Request extends Thread {
    public $url;
    public $data;
    public function __construct($url) {
        $this->url = $url;
    }
    public function run() {
        // 线程处理一个耗时5秒的任务
        for($i=0;$iurl);
        if ($response) {
            $this->data = array($response);
        }
        echo "线程: 任务完成\n";
    }
}
$request = new Request('hello.html');
// 运行线程:start()方法会触发run()运行
if ($request->start()) {
    // 主进程处理一个耗时10秒的任务,此时线程已经工作
    for($i=0;$ijoin();
    echo '线程返回数据: '.$request->data[0];
}
/*
如果顺序执行,合计时间将是15秒,借助线程,则只需10秒.
生成文件: echo 'Hello' > hello.html
运行计时: time php req.php 
查看线程: ps -efL|head -n1 && ps -efL|grep php
*/
</code>

聊一下php多线程的应用场合吧,例如php的pthreads

值得注意的是,不要在线程里使用echo输出内容,否则会出现不可预知的错误和行为,比如乱码(garbled).尤其是在非CLI环境下,比如Apache/PHP-FPM.

php就不要谈多线程了吧,哈哈

我也想知道.........................

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