学习C++并发编程笔记-条件变量

  1. 条件变量也是线程同步的方法
  2. std::condition_variable提供了两类操作:wait和notify。

#include "day4.hpp"
#include <iostream>
#include <mutex>
#include <condition_variable>
#include <thread>
#include <chrono>

namespace day4 {
std::mutex mutex;
std::condition_variable cv;
bool need_gone = false;
void TestWait() {
    std::unique_lock ul(mutex);
    std::cout << "TestWait start" << std::endl;
    cv.wait(ul);
    std::cout << "TestWait over" << std::endl;
//    cv.notify_all();
}

void TestNotify() {
    std::this_thread::sleep_for(std::chrono::seconds(5));
    std::unique_lock ul(mutex);
    for (int i = 0; i < 100; ++i) {
        if (i % 10 == 0) {
            std::cout << "TestNotify ...." << std::endl;
        }
    }
    std::cout << "TestNotify over" << std::endl;
    need_gone = true;
    cv.notify_all();
}

/*
 1. Windows虚假唤醒,异常唤醒和多核处理器有关系,是底层实现的问题,所以试图在应用层解释都是没有意义的
 2. 所以最好有一个条件判断
 */
void TestWait1() {
    std::unique_lock ul(mutex);
    std::cout << "TestWait1 start" << std::endl;
    while(need_gone == false) {
        cv.wait(ul);
    }
    std::cout << "TestWait1 over" << std::endl;
}
/*
 3. 还有一个判断条件
 */
void TestWait2() {
    std::unique_lock ul(mutex);
    std::cout << "TestWait2 start" << std::endl;
    cv.wait(ul, []() {
        return need_gone;
    });
    std::cout << "TestWait2 over" << std::endl;
}

/*
 4. wait_for, wait_for 可以指定一个时间段,在当前线程收到通知或者指定的时间 rel_time 超时之前,该线程都会处于阻塞状态。而一旦超时或者收到了其他线程的通知,wait_for 返回,剩下的处理步骤和 wait() 类似。
 */

void TestWait3() {
    std::unique_lock ul(mutex);
    std::cout << "TestWait3 start" << std::endl;
    cv.wait_for(ul, std::chrono::milliseconds(1));
    std::cout << "TestWait3 over" << std::endl;
}

void TestDay4() {
    std::thread t1(TestWait);
    std::thread t3(TestWait1);
    std::thread t4(TestWait2);
    std::thread t5(TestWait3);
    std::thread t2(TestNotify);
    t2.join();
    t1.join();
    t3.join();
    t4.join();
    t5.join();
    /*
     TestWait1 start
     TestWait2 start
     TestWait3 start
     TestWait start
     TestWait3 over
     TestNotify ....
     TestNotify ....
     TestNotify ....
     TestNotify ....
     TestNotify ....
     TestNotify ....
     TestNotify ....
     TestNotify ....
     TestNotify ....
     TestNotify ....
     TestNotify over
     TestWait1 over
     TestWait2 over
     TestWait over
     */
}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值