程序说明:输入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;
}