用于 PHP 的 pthreads 不在 Apache 中执行并行线程

问题描述:

我正在使用 PHP 的 pthreads 扩展.当我在 Windows 上从 cmd 执行 PHP 脚本时,我得到了并行线程,但是当我从 Apache 调用相同的脚本时,我得到了不同的结果,在我看来就像单线程执行一样.

I'm using the pthreads extension for PHP. When I execute the PHP script from cmd on Windows I get parallel threads but when I call the same script from Apache I get a different result and it seems to me like single thread execution.

是否应该为 Apache 进行任何配置以获得像 cmd(并行)这样的响应?

Is there any configuration that I should make for Apache to get response like cmd (parallel)?

class AsyncOperation extends Thread {
    public function __construct($arg){
        $this->arg = $arg;
    }

    public function run(){
        if($this->arg){
            for($i = 0; $i < 50; $i++) {
                echo "Yoo " . $this->arg . "<br>\n";
            }
        }
    }
}
$thread = new AsyncOperation("World ----------");
$thread2 = new AsyncOperation("Second -------------------------");
$thread->start();
$thread2->start();

for($i = 0; $i < 100; $i++) {
    echo "Standard <br>\n";
}

$thread->join();
$thread2->join();

示例代码在 cmd 中给出响应,例如:

Example code give response in cmd like:

Yoo World ----------<br>
Yoo World ----------<br>
Yoo World ----------<br>
Standard <br>
Standard <br>
Yoo World ----------<br>
Yoo Second -------------------------<br>
Standard <br>
Standard <br>

在网络浏览器中:

Yoo World ----------
Yoo World ----------
Yoo World ----------
Yoo World ----------
...
Yoo Second -------------------------
Yoo Second -------------------------
Yoo Second -------------------------
Yoo Second -------------------------
...
Standard 
Standard 
Standard 
Standard 
...

更新:在不同的浏览器上我得到不同的结果;此问题可能与缓冲区有关,我将对此进行调查.

Update: on different browsers I get different results; this problem might be related to buffer, which I'm going to investigate.

没有什么是模拟的,您正在执行真正的线程.

Nothing is simulated, you are executing real threads.

你不应该在SAPI模式下编写线程的标准输出,你会遇到无法控制的意外行为和错误,有太多的环境和SAPI无法很好地覆盖它,所以它根本没有覆盖,不要不要这样做.

You should not write the standard output from threads in SAPI mode, you will experience unexpected behaviour and errors, that cannot be controlled, there are too many environments and SAPI's to cover it well, so it is not covered at all, don't do it.

即使在 CLI 模式下,复杂代码的输出也会出现乱码,要解决此问题,您可以在传递给负责编写标准输出的所有上下文的任何对象中定义受保护的方法,如果该方法受保护且对象是 pthreads 的,一次只有一个上下文能够写入标准输出......通过将标准输出交换为日志数据库,可以在 SAPI 环境中使用相同的对象......

Even in CLI mode output of complex code will be garbled, to work around this, you can define a protected method in any object you pass to all contexts that takes care of writing standard output, if the method is protected and the object is a pthreads one, only one context will be able to write standard output at a time ... the same object could be used in the SAPI environment by swapping standard output for a logging database ...