用std::condition_variable 实现的生产者,消费者同步的例子

/* std c++ 多线程同步的例子
 * 用std::condition_variable 实现的生产者,消费者同步的例子
 * 当条件满足了,生产者生产出了产品,消费者再消费数据.
 * 消费者要等待,生产者要通知消费者消费.
 * 简单就是美!
 */
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
using namespace std;
std::queue<int> q;    //我们把数据存到队列里,当然不用队列也可以的. 顺便演示一下队列用法
std::mutex mtx;        //condition 的使用总是伴随者mutex 锁定
std::condition_variable cond;
void producer() //生产者线程
{
    for(int data=0;data<10;data++)
    {
        std::unique_lock<std::mutex> locker(mtx); //采用unique_lock 锁定mtx
        q.push(data);
        locker.unlock();        //释放锁
        cond.notify_one();  // Notify one waiting thread, if there is one
        std::this_thread::sleep_for(std::chrono::seconds(1)); //chrono 计时,是一个命名空间
    }
}
void consumer() //消费者线程,接受到数据9就退出
{
    int data = 0;
    while (data != 9)
    {
        std::unique_lock<std::mutex> locker(mtx); //采用unique_lock 锁定mtx
        while (q.empty())
            cond.wait(locker); // Unlock mtx and wait to be notified
        data = q.back();
        q.pop();
        locker.unlock();
        std::cout << "t2 got a value from t1: " << data << std::endl;
    }
}
int main()
{
    std::thread t1(producer); //创建线程对象t1, 以producer 函数为线程
    std::thread t2(consumer); //创建线程对象t2, 以consumer 函数为线程
    //主线程等待子线程执行完毕
    t1.join();
    t2.join();
    return 0;
}

 结果:

 ./test_thread_cpp
t2 got a value from t1: 0
t2 got a value from t1: 1
t2 got a value from t1: 2
t2 got a value from t1: 3
t2 got a value from t1: 4
t2 got a value from t1: 5
t2 got a value from t1: 6
t2 got a value from t1: 7
t2 got a value from t1: 8
t2 got a value from t1: 9

                        

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值