我在 C++ 中有两个线程。一个称为警报线程的线程运行该函数raiseAlarm()
,另一个称为打印线程的线程运行该函数printMetrics
。以固定的时间间隔,raiseAlarm
将原子变量设置为true
。当变量为true
时,printMetrics
基于该原子变量的值旋转的线程打印一些数据。当我运行这个应用程序时,什么也没有发生。但如果我在cout
任何地方放一个raiseAlarm
,一切正常。为什么?
void Client::raiseAlarm()
{
bool no = false;
while(!stop.load(std::memory_order_acquire))
{
//cout << "about to sleep\n";
this_thread::sleep_for(std::chrono::seconds(captureInterval));
while(!alarm.compare_exchange_weak(no, true, std::memory_order_acq_rel))
{
no = false;
}
}
}
void Client::printMetrics()
{
bool yes = true;
while(!stop.load(std::memory_order_acquire))
{
while(!alarm.compare_exchange_weak(yes, false, std::memory_order_acq_rel) )
{
yes = true;
}
cout << "Msgs Rcvd: " << metrics.rcv_total.load(std::memory_order_acquire);
cout << "Msgs Sent: " << metrics.snd_total.load(std::memory_order_acquire);
cout << "Min latency: " << metrics.min_latency.load(std::memory_order_acquire);
cout << "Max latency: " << metrics.max_latency.load(std::memory_order_acquire);
metrics.reset();
}
}