c++ boost 条件变量

程序说明:输入1:启动所有线程;输入0:挂起所以线程

//g++ main.cpp -lboost_system -lboost_thread -lpthread -std=c++11
#include <iostream>
#include <queue>
#include <boost/thread.hpp>

using namespace std;

boost::condition_variable cond1; //条件变量
boost::condition_variable cond2; //条件变量
boost::mutex bmutex1;  //互斥锁
boost::mutex bmutex2;
static int add = 0;
queue<int> q; //队列
static int input = 0;

void inputQueue()
{
    boost::unique_lock<boost::mutex> lock(bmutex2);  //加锁
    q.push(add);
    lock.unlock();   //解锁
    cond2.notify_all(); //激活所有线程

    usleep(500*1000);

    cout<<"queue push number is "<<add<<endl;
    add++;
}

void outputQueue()
{
    boost::unique_lock<boost::mutex> lock(bmutex2);
    if(q.empty()){
        cout<<"queue is empty"<<endl;
        sleep(1);
        cond2.wait(lock); //等待激活线程
    } else {
        cout<<"queue get number is "<<q.front()<<endl;//读取第一个
        q.pop(); //删除第一个
    }
    lock.unlock();
}

void stop_inputQueue(const int &id)
{
    while (1) {
        boost::unique_lock<boost::mutex> lock(bmutex1);
        while(input == 0) {
            cout<<"stop inputQueue thread"<<endl;
            cond1.wait(lock);
        }
//        cout<<"print inputQueue thread"<<endl;
        lock.unlock();
        inputQueue();

    }
}

void stop_outputQueue(const int &id)
{
    while (1) {
        boost::unique_lock<boost::mutex> lock(bmutex1);
        while(input == 0) {
            cout<<"stop outputQueue thread"<<endl;
            cond1.wait(lock);
        }
//        cout<<"print outputQueue thread"<<endl;
        lock.unlock();
        outputQueue();
    }
}

int main()
{
    cout << "Hello World!" << endl;

    boost::thread t_inputQueue(stop_inputQueue, NULL);
    boost::thread t_outputQueue(stop_outputQueue, NULL);

    while (1) {
        cout<<"please input(1/0) start process: ";
        cin>>input;

        switch (input) {
        case 1:
            cout<<"input is 1"<<endl;
            cout<<"start all thread"<<endl;
            cond1.notify_all();
            break;
        case 0:
            cout<<"input is 0"<<endl;
            break;
        default:
            cout<<"input neither 1 or 0"<<endl;
            break;
        }
    }

    t_inputQueue.join();
    t_outputQueue.join();

    return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值