我需要根据分钟间隔监控内部流量,所以我决定做这样的事情:
Flow{
void send();
static uint accumulator;
}
//Only single thread call to send
void Flow::sendPacket(pck){
accumulator+=pck.size();
do();
}
//Only single thread call to monitor . **No the same thread that call to send!**
Monitor::monitor(){
//Start monitor
Flow::accumulator = 0;
sleep(60);
rate = accumulator/60;
}
如果不使用 atomic,是否会有初始化为 0 的风险不会正确发生?
我担心的是,即使是 atomic 也不会保证 init,因为如果同时监视 init 为 0 并且同时使用旧值完成累积,那么新的累积值将基于旧值而不是基于初始值。
此外,我还担心原子惩罚。为每个数据包调用发送。
最佳答案
Volatile 对多线程没有帮助。您需要防止同时更新 accumulator
的值并在另一个线程正在读取值的同时更新。如果你有 C++11,你可以制作 accumulator
原子:std::atomic<uint> accumulator;
否则,您需要在所有对其值的访问周围锁定一个互斥量。
关于C++ 线程安全累加器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12180820/