zoukankan      html  css  js  c++  java
  • 条件变量 condition_variable wait

    wait(阻塞当前线程,直到条件变量被唤醒)

    #include <iostream>
    #include <string>
    #include <thread>
    #include <mutex>
    #include <condition_variable>
     
    std::mutex m;
    std::condition_variable cv;
    std::string data;
    bool ready = false;
    bool processed = false;
     
    void worker_thread()
    {
        // 等待直至 main() 发送数据
        std::unique_lock<std::mutex> lk(m);
        cv.wait(lk, []{return ready;});
     
        // 等待后,我们占有锁。
        std::cout << "Worker thread is processing data
    ";
        data += " after processing";
     
        // 发送数据回 main()
        processed = true;
        std::cout << "Worker thread signals data processing completed
    ";
     
        // 通知前完成手动解锁,以避免等待线程才被唤醒就阻塞(细节见 notify_one )
        lk.unlock();
        cv.notify_one();
    }
     
    int main()
    {
        std::thread worker(worker_thread);
     
        data = "Example data";
        // 发送数据到 worker 线程
        {
            std::lock_guard<std::mutex> lk(m);
            ready = true;
            std::cout << "main() signals data ready for processing
    ";
        }
        cv.notify_one();
     
        // 等候 worker
        {
            std::unique_lock<std::mutex> lk(m);
            cv.wait(lk, []{return processed;});
        }
        std::cout << "Back in main(), data = " << data << '
    ';
     
        worker.join();
    }
    
  • 相关阅读:
    区间DP——石子合并
    线性DP-最短编辑距离、编辑距离
    生成树协议
    交换机技术
    以太网原理
    接口知识点
    目前在中国有影响的几种现场总线比较
    委托
    C#有关继承知识点
    C#数组总结
  • 原文地址:https://www.cnblogs.com/smallredness/p/10904147.html
Copyright © 2011-2022 走看看