pthreads for PHP not executing parallel threads in Apache

*爱你&永不变心* 提交于 2019-12-04 11:26:25

问题


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.

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();

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>

In web browser:

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.


回答1:


Nothing is simulated, you are executing real threads.

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.

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



来源:https://stackoverflow.com/questions/15156503/pthreads-for-php-not-executing-parallel-threads-in-apache

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!