Threaded::notify
(PECL pthreads >= 2.0.0)
Threaded::notify — 同步控制
说明
public Threaded::notify(): bool
向对象发送唤醒通知
参数
此函数没有参数。
返回值
成功时返回 true
, 或者在失败时返回 false
。
范例
示例 #1 等待和唤醒
<?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());
?>
以上例程会输出:
bool(true)

User Contributed Notes 1 note
cottton at i-stats dot net ¶
7 years ago
Seems like some operators dont work.
f.e. $thread->array[] = 1; fails
a simple test:
<?php
class My extends Thread
{
public
$array = array('default val 1', 'default val 2'),
$msg = 'default',
$stop = false;
public function run()
{
while(true)
{
echo $this->msg . PHP_EOL;
if(count($this->array) > 0){
foreach($this->array as $val){
var_dump($val);
}
$this->array = array();
}
/** cause this thread to wait **/
$this->synchronized(
function($thread){
if(count($this->array) < 1){
$thread->wait();
}
},
$this
);
echo PHP_EOL;
if($this->stop){
break;
}
} // while
}
}
$my = new My();
$my->start();
sleep(1); // wait a bit
// test 1 - $thread->array[] = 1;
$my->synchronized(
function($thread){
$thread->msg = 'test 1';
$thread->array[] = 1;
$thread->notify();
},
$my
);
sleep(1); // wait a bit
// test 2 - array_push($thread->array, 2);
$my->synchronized(
function($thread){
$thread->msg = 'test 2';
array_push($thread->array, 2);
$thread->notify();
},
$my
);
sleep(1); // wait a bit
// test 3 - array_push($thread->array, 2);
$my->synchronized(
function($thread){
$thread->msg = 'test 3';
$new = array(3);
$thread->array = array_merge($thread->array, $new);
$thread->notify();
},
$my
);
sleep(1); // wait a bit
$my->stop = true;
?>
out:
default
string(13) "default val 1"
string(13) "default val 2"
test 1
test 2
test 3
int(3)
so in this case only array_merge() worked.