c ++线程安全累加器

Avi*_*ano 0 c++ multithreading

我需要根据分钟间隔监控内部流量,所以我决定做这样的事情:

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;
}
Run Code Online (Sandbox Code Playgroud)

我可以在没有使用原子的情况下初始化为0的风险不会发生吗?

我担心的是,即使是原子也不会保证init,因为如果同时监视init为0并且同时使用旧值进行累积,则新累积值将基于旧值而不是init值.

另外我关注原子惩罚.每个数据包都会调用send.

Pet*_*ker 5

易失性对多线程没有帮助.您需要accumulator在另一个线程正在读取值的同时防止同时更新值和更新.如果你有C++ 11,你可以创建accumulator原子:std::atomic<uint> accumulator;否则,你需要锁定所有访问其值的互斥锁.