暫停代碼如下:
$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)迷津。
1 回答

藍(lán)山帝景
TA貢獻(xiàn)1843條經(jīng)驗(yàn) 獲得超7個(gè)贊
這里的done
就是個(gè)普通的字段,和下面的用法其實(shí)是一樣的,都是PHP的基本用法:
class A {
}
$a = new A();
$a->done = true;
你的完整代碼應(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
還沒賦值,所以會執(zhí)行wait()
。而主線程接著會執(zhí)行notofy()
喚醒正在wait()
的子線程。
另一種情況是主線程先對done
賦值和執(zhí)行notify()
,然后再到子線程執(zhí)行run()
,這時(shí)子線程就不用wait
了,因?yàn)橹骶€程已經(jīng)notify()
了。
- 1 回答
- 0 關(guān)注
- 548 瀏覽
添加回答
舉報(bào)
0/150
提交
取消