C++ condition_variable 使用例程

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <chrono>

std::mutex mtx;
std::condition_variable cv;
bool ready = false;
bool use_cv = false;

void do_print_id(int id)
{
    bool test = true;
    std::cout << "thread begin " << id << std::endl;
    if (use_cv) {
        std::unique_lock<std::mutex> lck(mtx);
        while (!ready) {    // 如果不为true 则等待
            if (test) {
                std::cout << "begin to wait_for" << std::endl;
                // cv.wait(lck);       // 当前线程被阻塞 当全局标志为true后 线程被唤醒
                auto r = cv.wait_for(lck, std::chrono::milliseconds(1000));  // 需要根据wait_for返回值 是条件满足还是超时
                if (r == std::cv_status::timeout) {
                    std::cout << "cv_status::timeout." << std::endl;
                } else {
                    std::cout << "cv_status::no_timeout." << std::endl;
                }
            } else {
                std::cout << "thread " << id << " test sleep." << std::endl;
                std::this_thread::sleep_for(std::chrono::milliseconds(1000));
                test = true;
            }
        }         
            
    } else {
        // std::unique_lock<std::mutex> lck(mtx);
        // 如果在此处定义[std::unique_lock<std::mutex> lck(mtx);] 则第一个启动的线程则会一直在while中持有锁, 不释放;
        // 后面创建的线程 无法进入while循环
        while (!ready) {        // 如果不为true 则等待
            std::cout << "thread " << id << " wait." << std::endl;
            std::this_thread::sleep_for(std::chrono::milliseconds(1000));
        }
    }
    std::cout << "thread " << id << " End."<< std::endl;
}

void go()
{
    if (use_cv) {
        std::unique_lock<std::mutex> lck(mtx);
        ready = true;           // 设置全局标志为true
        cv.notify_all();        // 唤醒所有线程
    } else {
        ready = true;           // 设置全局标志为true
    }
}

int main()
{
    const int thread_size = 1;
    use_cv = true;
    std::thread threads[thread_size];
    for (int i = 0; i < thread_size; i++)
        threads[i] = std::thread(do_print_id, i); 

    #if 1
    for (auto& th:threads)
        th.detach();
    #else
    for (auto& th:threads)
        th.join();          // 如果使用join则会卡住 是因为10个线程都没有完全退出while
    #endif

    std::this_thread::sleep_for(std::chrono::milliseconds(3000));
    std::cout << "10 threads ready to race ... " << std::endl;
    go();

    while (1) {
        std::cout << "Main Loop" << std::endl;
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    }

    return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值