0

Say I have these 2 functions:

int* bigBuffer = new int[1024];
std::atomic<int> pos1 = 0;
volatile int pos2 = 0;

void push1(int value) {
    int offset = pos1.fetch_add(1, std::memory_order_acq_rel);
    bigBuffer[offset] = value;
}

void push2(int value) {
    int offset = pos2++;
    bigBuffer[offset] = value;
}

And then I have a multiple writer scenario where many threads call either push1 or push2 to store their data. The order of the data is not important, my main concern is speed.

From my limited testing, push2 is way faster and the data seems correct. Am I going to have problems with this down the road though?

user81993
  • 6,167
  • 6
  • 32
  • 64
  • 4
    _volatile_ is not about thread safety.\ – davmac Jun 27 '16 at 10:45
  • FWIW, the general guideline is to use std atomics for synchronization, and volatile only for volatile things like mem locations that can be changed by external hw such as actuators or DMA. – Erik Alapää Jun 27 '16 at 10:45
  • @davmac yes but afaik it forces the cpu not to cache the value which helps. Atomic variables have all kinds of guarantees but if I've understood it correctly, the only thing separating volatile from release/acquire atomics is access reordering which I don't need. They can race all they want as long as each of them gets a unique offset. – user81993 Jun 27 '16 at 10:49
  • @user81993 It doesn't force the CPU not to cache the value. It forces the compiler to re-load the value from memory when it is used, rather than keep it in a register; the CPU may have a local memory cache however. `volatile` doesn't ensure that multiple threads will see a consistent value. – davmac Jun 27 '16 at 10:59
  • @user81993 That's a myth. The use of `volatile` has no effect on CPU caches. (Also, why didn't you just code precisely what you need? C++ lets you do that. Why ask for `memory_order_acq_rel` if you don't need it?) – David Schwartz Jun 27 '16 at 11:02
  • @DavidSchwartz It was my impression that release and consume were the options with the least amount of overhead and I haven't figure out what the correct usage of consume is so acquire is supposedly a close second – user81993 Jun 27 '16 at 11:54
  • @user81993 No, they're the heaviest, you don't need them, and your other option doesn't provide them. Lightest is `memory_order_relaxed `. – David Schwartz Jun 27 '16 at 17:15

0 Answers0