C++ 线程安全累加器

标签 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;
}

如果不使用 atomic,是否会有初始化为 0 的风险不会正确发生?

我担心的是,即使是 atomic 也不会保证 init,因为如果同时监视 init 为 0 并且同时使用旧值完成累积,那么新的累积值将基于旧值而不是基于初始值。

此外,我还担心原子惩罚。为每个数据包调用发送。

最佳答案

Volatile 对多线程没有帮助。您需要防止同时更新 accumulator 的值并在另一个线程正在读取值的同时更新。如果你有 C++11,你可以制作 accumulator原子:std::atomic<uint> accumulator;否则,您需要在所有对其值的访问周围锁定一个互斥量。

关于C++ 线程安全累加器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12180820/

相关文章:

c++ - 我可以退回拷贝作为引用吗?

c++ - size_type 和 int 之间的区别

c++ - 获取控制台句柄

c++ - 线程通信中消息队列相对于共享数据的优势是什么?

android - 等待 Activity 显示

python - Julia >=1.3 和 Python 3.x 中的多线程模型比较

multithreading - Hadoop 可以减少 SIFT 的运行时间吗?

c - 我正在使用 SIMD 和 pthreads 做什么,这会减慢我的程序速度?

c++ - 如何使用目标接口(interface)将编译选项添加到 CMake FetchContent 依赖项

c++ - 如何设置和获取 fipTag 的值