基本上,我有两个主题:
ONE:从用户获取消息,并将其添加到队列中。 - 通知另一个线程队列/
中有消息TWO:处理消息并将其打印出来,等待另一个线程通知他们:
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
void getMessages();
void handleMessages();
using namespace std;
queue<int> msgQueue;
mutex mLock;
condition_variable con;
int main(void)
{
thread msgHandle(handleMessages);
getMessages();
msgHandle.join();
}
// getting messages from user
void getMessages()
{
int num = 0;
do
{
// getting number from user
cin >> num;
// adding number to queue
mLock.lock();
msgQueue.push(num);
mLock.unlock();
// notifying
con.notify_one();
} while (num != -1);
}
// handles the message queue
void handleMessages()
{
int curNum = 0;
do
{
// waiting for reply
unique_lock<mutex> uLock(mLock);
try
{
con.wait(uLock);
}
catch (...)
{
break;
}
// printing message from queue
curNum = msgQueue.front();
msgQueue.pop();
cout << "Number: " << curNum << endl;
} while (curNum != -1);
}
我的问题是如果手动退出应用程序(X按钮)
,如何中止等待部分