我有一个跨平台的c ++程序,我正在使用boost库来创建一个异步计时器.
我有一个全局变量:
bool receivedInput = false;
Run Code Online (Sandbox Code Playgroud)
一个线程等待并处理输入
string argStr;
while (1)
{
getline(cin, argStr);
processArguments(argStr);
receivedInput = true;
}
Run Code Online (Sandbox Code Playgroud)
另一个线程运行一个计时器,每10秒调用一次回调.在该回调中,我检查是否收到了消息
if (receivedInput)
{
//set up timer to fire again in 10 seconds
receivedInput = false;
}
else
exit(1);
Run Code Online (Sandbox Code Playgroud)
这样安全吗?对于线程2中的读取,我认为无关紧要,因为条件将评估为true或false.但我不确定如果两个线程同时尝试设置receivedInput会发生什么.我也把我的计时器比我期望接收输入的时间长3倍,所以我不担心比赛情况.
编辑:为了解决这个问题,我在读取receivedInput时设置了receiveInput和boost :: shared_lock时使用了boost :: unique_lock.我在这里用了一个例子