惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Microsoft Azure Blog
Microsoft Azure Blog
J
Java Code Geeks
量子位
腾讯CDC
C
Check Point Blog
小众软件
小众软件
IT之家
IT之家
I
InfoQ
Hugging Face - Blog
Hugging Face - Blog
Stack Overflow Blog
Stack Overflow Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
GbyAI
GbyAI
Apple Machine Learning Research
Apple Machine Learning Research
大猫的无限游戏
大猫的无限游戏
博客园_首页
S
SegmentFault 最新的问题
The Cloudflare Blog
阮一峰的网络日志
阮一峰的网络日志
aimingoo的专栏
aimingoo的专栏
P
Proofpoint News Feed
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Google DeepMind News
Google DeepMind News
T
Tailwind CSS Blog
Martin Fowler
Martin Fowler

博客园 - xcywt

IT人备考心得分享 一个大龄程序员的回乡记 一种刚接触的语法。只在linux可用 固件打包流程 malloc底层实现以及和new的比较 C++异步调用 future async promise packaged_task 如果在单例模式中返回share_ptr ??? 记录一道面试题(哈希表 稀疏矩阵) Qt实现自定义控件-按钮 一个线程池的例子 C++中share_ptr中循环引用的问题 C++14的一些新特性 C++11的一些特性 ubuntu编译grpc & protobuf perf笔记 一个cmakelist的例子(自动处理多个proto) Linux下eCal测试计划及进度记录 windows编译ecal 记录一次重装gitlab
C++ 条件变量condition_variable的例子
xcywt · 2024-09-23 · via 博客园 - xcywt

C++标准库对条件变量有两套实现:std::condition_variable 和 std::condition_variable_any 。 这两个实现都包含在 <condition_variable> 头文件的声明中。 两者都需要与一个互斥量一起才能工作(互斥量是为了同步); 前者仅限于与 std::mutex 一起工作, 而后者可以和任何满足最低标准的互斥量一起工作, 从而加上了_any的后缀。  

直接上代码:

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

class conditionTest {
public:
    conditionTest()
    {
        m_th = std::thread(std::bind(&conditionTest::MyThreadLoop, this));
        m_th2 = std::thread(std::bind(&conditionTest::MyThreadLoop2222, this));
    }
    ~conditionTest() {  }
    void MyThreadLoop()
    {
        while (1)
        {
            std::this_thread::sleep_for(std::chrono::milliseconds(1000));
            std::unique_lock<std::mutex> locker(_mutex);
            mmmm++;
            printf("MyThreadLoop AAAAAAAAAAAAAAAAAA mmmm:%d \n", mmmm);
            conTTT.notify_one();
        }
    }

    void MyThreadLoop2222()
    {
        while (1)
        {
            std::this_thread::sleep_for(std::chrono::milliseconds(1));
            std::unique_lock<std::mutex> locker(_mutex);
            conTTT.wait(locker); // 这里会先解锁(允许别人加锁),再进入等待状态。
            printf("MyThreadLoop2222 BBBBBBBBBBBBBBBBBB mmmm:%d \n", mmmm);
            std::this_thread::sleep_for(std::chrono::milliseconds(10));
        }
    }

    std::thread m_th;
    std::thread m_th2;
    std::mutex _mutex;
    std::condition_variable_any conTTT;
    int mmmm = 0;
};

int main()
{
    conditionTest tt;
    system("pause");
    return 0;
}