鍍金池/ 問答/PHP  Python  Linux/ php多線程pthread的$thread->done是啥玩意?。?/span>

php多線程pthread的$thread->done是啥玩意?。?/h1>

暫停代碼如下:

$this->synchronized(function($thread){
    if (!$thread->done)
        $thread->wait();
}, $this);

喚醒代碼如下:

$my->synchronized(function($thread){
    $thread->done = true;
    $thread->notify();
}, $my);

那么......那個(gè)thread->done到底是個(gè)什么玩意?為什么我去掉了程序依然跑得通?
懇請各位大佬指點(diǎn)迷津。

回答
編輯回答
青檸

這里的done就是個(gè)普通的字段,和下面的用法其實(shí)是一樣的,都是PHP的基本用法:

class A {
}

$a = new A();
$a->done = true;

Run

你的完整代碼應(yīng)該pthread里的實(shí)例吧:

<?php
class My extends Thread {
    public function run() {
        $this->synchronized(function($thread){
            if (!$thread->done)
                $thread->wait();
        }, $this);
    }
}
$my = new My();
$my->start();
$my->synchronized(function($thread){
    $thread->done = true;
    $thread->notify();
}, $my);
var_dump($my->join());

start()的時(shí)候開始在子線程里跑run(),這是done還沒賦值,所以會(huì)執(zhí)行wait()。而主線程接著會(huì)執(zhí)行notofy()喚醒正在wait()的子線程。

另一種情況是主線程先對done賦值和執(zhí)行notify(),然后再到子線程執(zhí)行run(),這時(shí)子線程就不用wait了,因?yàn)橹骶€程已經(jīng)notify()了。

2017年10月14日 13:12