zoukankan      html  css  js  c++  java
  • 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()发送唤醒通知,线程才执行。
  • 相关阅读:
    day74 作业
    day73 基表 表关联
    不知道第几次分享了
    day72 序列化家族
    day72 作业
    vscode
    vuex
    linux python3.7的安装和配置
    使用多线程分批发送短信代码,分割list
    docker 容器里使用crontab不生效
  • 原文地址:https://www.cnblogs.com/jkko123/p/6294593.html
Copyright © 2011-2022 走看看