7

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

我应该为 Apache 进行任何配置以获取类似cmd(并行)的响应吗?

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

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 
...

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

4

1 回答 1

2

没有任何东西是模拟的,你正在执行真正的线程。

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

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

于 2013-03-02T12:52:45.567 回答