php Pthread 多线程 (五) 线程同步
发布时间:2020-05-31 00:09:03 所属栏目:PHP 来源:互联网
导读:有些时候我们不希望线程调用start()后就立刻执行,在处理完我们的业务逻辑后在需要的时候让线程执行。 lt;?php class Sync extends Thread { private $na
|
有些时候我们不希望线程调用start()后就立刻执行,在处理完我们的业务逻辑后在需要的时候让线程执行。 <?php
class Sync extends Thread {
private $name = '';
public function __construct($name) {
$this->name = $name;
}
public function run() {
//让线程进入等待状态
$this->synchronized(function($self){
$self->wait();
},$this);
echo "thread {$this->name} run... rn";
}
}
//我们创建10个线程
$threads = array();
for($ix = 0; $ix < 10; ++$ix) {
$thread = new Sync($ix);
$thread->start();
$threads[] = $thread;
}
$num = 1;
while(true) {
if($num > 5) {
//当$num大于5时,我们才唤醒线程让它们执行
foreach($threads as $thread) {
$thread->synchronized(function($self){
$self->notify();
},$thread);
}
break;
}
//这里我们处理我们需要的代码
//这时候线程是处在等待状态的
echo "wait... rn";
sleep(3);
++$num;
}
foreach($threads as $thread) {
$thread->join();
}
echo "end... rn";
10个线程在start后并没有立刻执行,而是等待中,直到通过notify()发送唤醒通知,线程才执行。 (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
