Better_Software_Header_MobileBetter_Software_Header_Web

Find what you need - explore our website and developer resources

A Race is a Race is a Race is UB

An example of the difference between int, volatile int, and std::atomic


static CounterType counter; // global, zero-initialised

// in some function:
for (...)
   ++counter; // or counter.fetch_add(1, std::memory_order_relaxed) for relaxed atomics

register r = 0;
for (...)
    ++r;
counter.fetch_add(r, std::memory_order_relaxed); // atomic operation

register r = counter;
for (...)
    ++r;
counter = r;

// counter initially zero
// T1                T2

r1 = counter;        r2 = counter;    // r1 == 0, r2 == 0
for (c1 times)       for (c2 times)
    ++r1;                ++r2;
                                      // r1 == c1, r2 == c2
counter = r;                          // counter == c1
                     counter = r;     // counter == c2 !! correct result would be: c1 + c2