1

所以,我想在 PHP 中创建一个异步 Web 服务。为什么?因为我有一个不错的异步前端,但如果我有超过 6 个活动 TCP 连接,Chrome 会阻止我的请求。当然,我读过一些类似的问题,例如:

但这些不包括我的问题。

我安装pthreads的目的是让我能够在不同的线程中发出多个请求,这样我的 PHP 就不会阻塞其他请求(在我的情况下,我开始了一个长进程,如果进程是,我希望能够轮询是否仍然忙碌)。

PHPReact 似乎是一个不错的库(非阻塞 I/O,异步),但这也不起作用(仍然同步)。

我是否遗漏了什么,或者现在这在 PHP 中仍然是不可能的?

class Example{
    private $url;   
    function __construct($url){
        $this->url = $url;
        echo 'pooooof request to ' . $this->url . ' sent <br />';
        $request = new Request($this->url);     
        $request->start();
    }
}

class Request extends Thread{
    private $url;   
    function __construct($url){
        $this->url = $url;
    }

    function run(){
        // execute curl, multi_curl, file_get_contents but every request is sync
    }
}

new Example('https://gtmetrix.com/why-is-my-page-slow.html');
new Example('http://php.net/manual/en/function.file-get-contents.php');
new Example('https://www.google.nl/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=php%20file%20get%20contents'); 

理想的情况是使用回调。

附言。我见过一些提供此功能的服务器(如 Node.js),但我更喜欢本机方法。当这不可能时,我真的在考虑切换到 Python、Java、Scala 或其他支持异步的语言。

4

1 回答 1

3

我真的无法理解你在做什么......

  • 异步和并行是不可互换的词。
  • Web 应用程序前端的线程没有意义。
  • 您不需要线程来使许多 I/O 绑定任务并发;这就是非阻塞 I/O 的用途(异步并发)。
  • 并行并发在这里似乎有点矫枉过正。

无论如何,您的请求出现同步的原因是此构造函数的编写方式:

function __construct($url){
    $this->url = $url;
    echo 'pooooof request to ' . $this->url . ' sent <br />';
    $request = new Request($this->url);     
    $request->start();
}

线程将Request在控制权返回给__construct(new) 的调用者之前加入,因为变量超出范围,因此被销毁(加入是销毁的一部分)。

于 2015-08-13T08:20:22.187 回答