php Pthread 多线程 (五) 线程同步

有些时候我们不希望线程调用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... 
";
    }
}

//我们创建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... 
";
    sleep(3);
    ++$num;
}

foreach($threads as $thread) {
    $thread->join();
}
echo "end... 
";
10个线程在start后并没有立刻执行,而是等待中,直到通过notify()发送唤醒通知,线程才执行。
原文地址:https://www.cnblogs.com/jkko123/p/6294593.html