栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

c++ 条件变量使用例子

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

c++ 条件变量使用例子

#include 
#include 
#include 
#include 
#include 

std::condition_variable m_cv;
std::mutex m_mutex;
std::atomic AtomicInt;

typedef void *(*FOSThreadRoutine)(int &);

void *AudioRecvThread(int &i)
{
    while (1)
    {
        i = AtomicInt;
        while (AtomicInt % 2 == 0)
        {
            std::unique_lock lock(m_mutex);//自解锁
            m_cv.wait(lock);//等待唤醒的信号
            std::thread::id this_id = std::this_thread::get_id();
            std::cout << "this_id= " << this_id << " wait" << std::endl;
        }

        std::thread::id this_id = std::this_thread::get_id();
        std::cout << " this_id= " << this_id << ",i=" << i << std::endl
                  << std::endl;
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    }
}

int main(void)
{

    FOSThreadRoutine fnRoutine;
    fnRoutine = AudioRecvThread;

    int i = 0;
    std::thread hd_ = std::move(std::thread(fnRoutine, std::ref(i)));//如果要传引用进去,需要使用std::ref;

    while (1)
    {
        int i = 0;
        std::cin >> i;
        std::cout << "手动输入 i = " << i << std::endl;
        AtomicInt = i;
        m_cv.notify_one();
    }

    hd_.join();

    return 1;
}


程序运行后,手动输入整数,会有不同的输出;偶数等待,奇数持续运行;

运行结果:

[root@localhost test]# ./test
1
手动输入 i = 1
this_id= 139770932119296 wait  //输入奇数将持续运行下去,不会停止;
 this_id= 139770932119296,i=0

 this_id= 139770932119296,i=1

 this_id= 139770932119296,i=1

 this_id= 139770932119296,i=1

2
手动输入 i = 2//第一次运行到此处,m_cv.wait(lock);将等待信号
2
手动输入 i = 2
this_id= 139770932119296 wait//第一次输入2后被阻塞,在收到 m_cv.notify_one();后解除等待,接着输出此句;
2
手动输入 i = 2
this_id= 139770932119296 wait
2
手动输入 i = 2
this_id= 139770932119296 wait
3
手动输入 i = 3
this_id= 139770932119296 wait
 this_id= 139770932119296,i=2

 this_id= 139770932119296,i=3

 this_id= 139770932119296,i=3

 this_id= 139770932119296,i=3

9 this_id= 139770932119296,i=3

99
手动输入 i = 999
 this_id= 139770932119296,i=999

 this_id= 139770932119296,i=999

 this_id= 139770932119296,i=999


 this_id= 139770932119296,i=999

 this_id= 139770932119296,i=999

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1022802.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号