Avihai Marchiano
Avihai Marchiano

Reputation: 3927

c++ Thread safe accumulator

I need to monitor internal traffic based on minute interval , so i decide to do something like this:

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

Can i have without use atomic a risk that initialize to 0 will not happened correct?

My concern is that even atomic will not guaranty init, because if at the same time monitor init it to 0 and at the same time accumulate is done with old value than new accumulate value will be based in the old value and not on the init value.

In additional i concern from the atomic penalty. send is called for every packet.

Upvotes: 0

Views: 1162

Answers (2)

Mike Seymour
Mike Seymour

Reputation: 254461

volatile is neither necessary nor sufficient for sharing data between threads, so don't use it.

If it might be accessed by more than one thread, then you must either:

  • make the accesses atomic, using the C++11 atomics library, or compiler-specific language extensions if that's not available, or
  • guard it with a mutex or similar lock, using the C++11 threading library, or some other library (Boost.Thread, POSIX threads, Intel TBB, Windows API, or numerous others) if that's not available.

Otherwise, you will have a data race, giving undefined behaviour.

If only one thread can access it, then you don't need to do anything special.

Upvotes: 1

Pete Becker
Pete Becker

Reputation: 76295

Volatile doesn't help with multi-threading. You need to prevent simultaneous updates to the value of accumulator and updates at the same time that another thread is reading the value. If you have C++11 you can make accumulator atomic: std::atomic<uint> accumulator; Otherwise, you need to lock a mutex around all accesses to its value.

Upvotes: 5

Related Questions