ChatGPT解决这个技术问题 Extra ChatGPT

Can num++ be atomic for 'int num'?

In general, for int num, num++ (or ++num), as a read-modify-write operation, is not atomic. But I often see compilers, for example GCC, generate the following code for it (try here):

void f()
{
  int num = 0;
  num++;
}
f():
        push    rbp
        mov     rbp, rsp
        mov     DWORD PTR [rbp-4], 0
        add     DWORD PTR [rbp-4], 1
        nop
        pop     rbp
        ret

Since line 5, which corresponds to num++ is one instruction, can we conclude that num++ is atomic in this case?

And if so, does it mean that so-generated num++ can be used in concurrent (multi-threaded) scenarios without any danger of data races (i.e. we don't need to make it, for example, std::atomic<int> and impose the associated costs, since it's atomic anyway)?

UPDATE

Notice that this question is not whether increment is atomic (it's not and that was and is the opening line of the question). It's whether it can be in particular scenarios, i.e. whether one-instruction nature can in certain cases be exploited to avoid the overhead of the lock prefix. And, as the accepted answer mentions in the section about uniprocessor machines, as well as this answer, the conversation in its comments and others explain, it can (although not with C or C++).

Who told you that add is atomic?
given that one of the features of atomics is prevention of specific kinds of reordering during optimization, no, regardless of the atomicity of the actual operation
I would also like to point out that if this is atomic on your platform there is no guarantee that it will be on another pltaform. Be platform independent and express your intention by using a std::atomic<int>.
During the execution of that add instruction, another core could steal that memory address from this core's cache and modify it. On an x86 CPU, the add instruction needs a lock prefix if the address needs to be locked in cache for the duration of the operation.
It is possible for any operation to happen to be "atomic." All you have to do is get lucky and never happen to execute anything which would reveal that it is not atomic. Atomic is only valuable as a guarantee. Given that you're looking at assembly code, the question is whether that particular architecture happens to provide you the guarantee and whether the compiler provides a guarantee that that's the assembly level implementation they choose.

P
Peter Cordes

This is absolutely what C++ defines as a Data Race that causes Undefined Behaviour, even if one compiler happened to produce code that did what you hoped on some target machine. You need to use std::atomic for reliable results, but you can use it with memory_order_relaxed if you don't care about reordering. See below for some example code and asm output using fetch_add.

But first, the assembly language part of the question:

Since num++ is one instruction (add dword [num], 1), can we conclude that num++ is atomic in this case?

Memory-destination instructions (other than pure stores) are read-modify-write operations that happen in multiple internal steps. No architectural register is modified, but the CPU has to hold the data internally while it sends it through its ALU. The actual register file is only a small part of the data storage inside even the simplest CPU, with latches holding outputs of one stage as inputs for another stage, etc., etc.

Memory operations from other CPUs can become globally visible between the load and store. I.e. two threads running add dword [num], 1 in a loop would step on each other's stores. (See @Margaret's answer for a nice diagram). After 40k increments from each of two threads, the counter might have only gone up by ~60k (not 80k) on real multi-core x86 hardware.

"Atomic", from the Greek word meaning indivisible, means that no observer can see the operation as separate steps. Happening physically / electrically instantaneously for all bits simultaneously is just one way to achieve this for a load or store, but that's not even possible for an ALU operation. I went into a lot more detail about pure loads and pure stores in my answer to Atomicity on x86, while this answer focuses on read-modify-write.

The lock prefix can be applied to many read-modify-write (memory destination) instructions to make the entire operation atomic with respect to all possible observers in the system (other cores and DMA devices, not an oscilloscope hooked up to the CPU pins). That is why it exists. (See also this Q&A).

So lock add dword [num], 1 is atomic. A CPU core running that instruction would keep the cache line pinned in Modified state in its private L1 cache from when the load reads data from cache until the store commits its result back into cache. This prevents any other cache in the system from having a copy of the cache line at any point from load to store, according to the rules of the MESI cache coherency protocol (or the MOESI/MESIF versions of it used by multi-core AMD/Intel CPUs, respectively). Thus, operations by other cores appear to happen either before or after, not during.

Without the lock prefix, another core could take ownership of the cache line and modify it after our load but before our store, so that other store would become globally visible in between our load and store. Several other answers get this wrong, and claim that without lock you'd get conflicting copies of the same cache line. This can never happen in a system with coherent caches.

(If a locked instruction operates on memory that spans two cache lines, it takes a lot more work to make sure the changes to both parts of the object stay atomic as they propagate to all observers, so no observer can see tearing. The CPU might have to lock the whole memory bus until the data hits memory. Don't misalign your atomic variables!)

Note that the lock prefix also turns an instruction into a full memory barrier (like MFENCE), stopping all run-time reordering and thus giving sequential consistency. (See Jeff Preshing's excellent blog post. His other posts are all excellent, too, and clearly explain a lot of good stuff about lock-free programming, from x86 and other hardware details to C++ rules.)

On a uniprocessor machine, or in a single-threaded process, a single RMW instruction actually is atomic without a lock prefix. The only way for other code to access the shared variable is for the CPU to do a context switch, which can't happen in the middle of an instruction. So a plain dec dword [num] can synchronize between a single-threaded program and its signal handlers, or in a multi-threaded program running on a single-core machine. See the second half of my answer on another question, and the comments under it, where I explain this in more detail.

Back to C++:

It's totally bogus to use num++ without telling the compiler that you need it to compile to a single read-modify-write implementation:

;; Valid compiler output for num++
mov   eax, [num]
inc   eax
mov   [num], eax

This is very likely if you use the value of num later: the compiler will keep it live in a register after the increment. So even if you check how num++ compiles on its own, changing the surrounding code can affect it.

(If the value isn't needed later, inc dword [num] is preferred; modern x86 CPUs will run a memory-destination RMW instruction at least as efficiently as using three separate instructions. Fun fact: gcc -O3 -m32 -mtune=i586 will actually emit this, because (Pentium) P5's superscalar pipeline didn't decode complex instructions to multiple simple micro-operations the way P6 and later microarchitectures do. See the Agner Fog's instruction tables / microarchitecture guide for more info, and the tag wiki for many useful links (including Intel's x86 ISA manuals, which are freely available as PDF)).

Don't confuse the target memory model (x86) with the C++ memory model

Compile-time reordering is allowed. The other part of what you get with std::atomic is control over compile-time reordering, to make sure your num++ becomes globally visible only after some other operation.

Classic example: Storing some data into a buffer for another thread to look at, then setting a flag. Even though x86 does acquire loads/release stores for free, you still have to tell the compiler not to reorder by using flag.store(1, std::memory_order_release);.

You might be expecting that this code will synchronize with other threads:

// int flag;  is just a plain global, not std::atomic<int>.
flag--;           // Pretend this is supposed to be some kind of locking attempt
modify_a_data_structure(&foo);    // doesn't look at flag, and the compiler knows this.  (Assume it can see the function def).  Otherwise the usual don't-break-single-threaded-code rules come into play!
flag++;

But it won't. The compiler is free to move the flag++ across the function call (if it inlines the function or knows that it doesn't look at flag). Then it can optimize away the modification entirely, because flag isn't even volatile.

(And no, C++ volatile is not a useful substitute for std::atomic. std::atomic does make the compiler assume that values in memory can be modified asynchronously similar to volatile, but there's much more to it than that. (In practice there are similarities between volatile int to std::atomic with mo_relaxed for pure-load and pure-store operations, but not for RMWs). Also, volatile std::atomic<int> foo is not necessarily the same as std::atomic<int> foo, although current compilers don't optimize atomics (e.g. 2 back-to-back stores of the same value) so volatile atomic wouldn't change the code-gen.)

Defining data races on non-atomic variables as Undefined Behaviour is what lets the compiler still hoist loads and sink stores out of loops, and many other optimizations for memory that multiple threads might have a reference to. (See this LLVM blog for more about how UB enables compiler optimizations.)

As I mentioned, the x86 lock prefix is a full memory barrier, so using num.fetch_add(1, std::memory_order_relaxed); generates the same code on x86 as num++ (the default is sequential consistency), but it can be much more efficient on other architectures (like ARM). Even on x86, relaxed allows more compile-time reordering.

This is what GCC actually does on x86, for a few functions that operate on a std::atomic global variable.

See the source + assembly language code formatted nicely on the Godbolt compiler explorer. You can select other target architectures, including ARM, MIPS, and PowerPC, to see what kind of assembly language code you get from atomics for those targets.

#include <atomic>
std::atomic<int> num;
void inc_relaxed() {
  num.fetch_add(1, std::memory_order_relaxed);
}

int load_num() { return num; }            // Even seq_cst loads are free on x86
void store_num(int val){ num = val; }
void store_num_release(int val){
  num.store(val, std::memory_order_release);
}
// Can the compiler collapse multiple atomic operations into one? No, it can't.
# g++ 6.2 -O3, targeting x86-64 System V calling convention. (First argument in edi/rdi)
inc_relaxed():
    lock add        DWORD PTR num[rip], 1      #### Even relaxed RMWs need a lock. There's no way to request just a single-instruction RMW with no lock, for synchronizing between a program and signal handler for example. :/ There is atomic_signal_fence for ordering, but nothing for RMW.
    ret
inc_seq_cst():
    lock add        DWORD PTR num[rip], 1
    ret
load_num():
    mov     eax, DWORD PTR num[rip]
    ret
store_num(int):
    mov     DWORD PTR num[rip], edi
    mfence                          ##### seq_cst stores need an mfence
    ret
store_num_release(int):
    mov     DWORD PTR num[rip], edi
    ret                             ##### Release and weaker doesn't.
store_num_relaxed(int):
    mov     DWORD PTR num[rip], edi
    ret

Notice how MFENCE (a full barrier) is needed after a sequential-consistency stores. x86 is strongly ordered in general, but StoreLoad reordering is allowed. Having a store buffer is essential for good performance on a pipelined out-of-order CPU. Jeff Preshing's Memory Reordering Caught in the Act shows the consequences of not using MFENCE, with real code to show reordering happening on real hardware.

Re: discussion in comments on @Richard Hodges' answer about compilers merging std::atomic num++; num-=2; operations into one num--; instruction:

A separate Q&A on this same subject: Why don't compilers merge redundant std::atomic writes?, where my answer restates a lot of what I wrote below.

Current compilers don't actually do this (yet), but not because they aren't allowed to. C++ WG21/P0062R1: When should compilers optimize atomics? discusses the expectation that many programmers have that compilers won't make "surprising" optimizations, and what the standard can do to give programmers control. N4455 discusses many examples of things that can be optimized, including this one. It points out that inlining and constant-propagation can introduce things like fetch_or(0) which may be able to turn into just a load() (but still has acquire and release semantics), even when the original source didn't have any obviously redundant atomic ops.

The real reasons compilers don't do it (yet) are: (1) nobody's written the complicated code that would allow the compiler to do that safely (without ever getting it wrong), and (2) it potentially violates the principle of least surprise. Lock-free code is hard enough to write correctly in the first place. So don't be casual in your use of atomic weapons: they aren't cheap and don't optimize much. It's not always easy easy to avoid redundant atomic operations with std::shared_ptr<T>, though, since there's no non-atomic version of it (although one of the answers here gives an easy way to define a shared_ptr_unsynchronized<T> for gcc).

Getting back to num++; num-=2; compiling as if it were num--: Compilers are allowed to do this, unless num is volatile std::atomic<int>. If a reordering is possible, the as-if rule allows the compiler to decide at compile time that it always happens that way. Nothing guarantees that an observer could see the intermediate values (the num++ result).

I.e. if the ordering where nothing becomes globally visible between these operations is compatible with the ordering requirements of the source (according to the C++ rules for the abstract machine, not the target architecture), the compiler can emit a single lock dec dword [num] instead of lock inc dword [num] / lock sub dword [num], 2.

num++; num-- can't disappear, because it still has a Synchronizes With relationship with other threads that look at num, and it's both an acquire-load and a release-store which disallows reordering of other operations in this thread. For x86, this might be able to compile to an MFENCE, instead of a lock add dword [num], 0 (i.e. num += 0).

As discussed in PR0062, more aggressive merging of non-adjacent atomic ops at compile time can be bad (e.g. a progress counter only gets updated once at the end instead of every iteration), but it can also help performance without downsides (e.g. skipping the atomic inc / dec of ref counts when a copy of a shared_ptr is created and destroyed, if the compiler can prove that another shared_ptr object exists for entire lifespan of the temporary.)

Even num++; num-- merging could hurt fairness of a lock implementation when one thread unlocks and re-locks right away. If it's never actually released in the asm, even hardware arbitration mechanisms won't give another thread a chance to grab the lock at that point.

With current gcc6.2 and clang3.9, you still get separate locked operations even with memory_order_relaxed in the most obviously optimizable case. (Godbolt compiler explorer so you can see if the latest versions are different.)

void multiple_ops_relaxed(std::atomic<unsigned int>& num) {
  num.fetch_add( 1, std::memory_order_relaxed);
  num.fetch_add(-1, std::memory_order_relaxed);
  num.fetch_add( 6, std::memory_order_relaxed);
  num.fetch_add(-5, std::memory_order_relaxed);
  //num.fetch_add(-1, std::memory_order_relaxed);
}

multiple_ops_relaxed(std::atomic<unsigned int>&):
    lock add        DWORD PTR [rdi], 1
    lock sub        DWORD PTR [rdi], 1
    lock add        DWORD PTR [rdi], 6
    lock sub        DWORD PTR [rdi], 5
    ret

"[using separate instructions] used to be more efficient ... but modern x86 CPUs once again handle RMW operations at least as efficiently" -- it still is more efficient in the case where the updated value will be used later in the same function and there's a free register available for the compiler to store it in (and the variable isn't marked volatile, of course). This means that it is highly likely that whether the compiler generates a single instruction or multiple for the operation depends on the rest of the code in the function, not just the single line in question.
@DavidC.Rankin: If you have any edits you'd like to make, feel free. I don't want to make this CW, though. It's still my work (and my mess :P). I'll tidy up some after my Ultimate [frisbee] game :)
If not community wiki, then maybe a link on the appropriate tag wiki. (both the x86 and atomic tags?). It's worth additional linkage rather than a hopeful return by a generic search on S.O. (If I knew better where it should fit in that regard, I'd do it. I'll have to dig further into the do's & don't's of tag wiki linkage)
As always - great answer! Good distinction between coherence and atomicity (where some others got it wrong)
@МаксФедотов: Ok, interesting, thanks for finding that exact wording. I guess that's a possible hardware design, but I'm not sure real CPUs are designed that way. It sounds to me like an alternate mental model for OoO early exec of loads. I'm not in a position to say for sure; might make an interesting SO question on its own, if there isn't already a duplicate. Feel free to quote or paraphrase any of my comments here if you want to ask such a question. I've never seen a CPU vendor advertize a new version having a larger "invalidate queue" for better memory parallelism, only load buffers.
M
Margaret Bloom

Without many complications an instruction like add DWORD PTR [rbp-4], 1 is very CISC-style.

It perform three operations: load the operand from memory, increment it, store the operand back to memory. During these operations the CPU acquire and release the bus twice, in between any other agent can acquire it too and this violates the atomicity.

AGENT 1          AGENT 2

load X              
inc C
                 load X
                 inc C
                 store X
store X

X is incremented only once.


@LeoHeinsaar In order for that to be the case, each memory chip would need its own Arithmetic Logic Unit (ALU). It would, in effect, require that each memory chip was a processor.
@LeoHeinsaar: memory-destination instructions are read-modify-write operations. No architectural register is modified, but the CPU has to hold the data internally while it sends it through its ALU. The actual register file is only a small part of the data storage inside even the simplest CPU, with latches holding outputs of one stage as inputs for another stage, etc. etc.
@PeterCordes Your comment is exactly the answer I was looking for. Margaret's answer made me suspect that something like that must go on inside.
Turned that comment into a full answer, including addressing the C++ part of the question.
@PeterCordes Thanks, very detailed and on all points. It was obviously a data race and therefore undefined behavior by the C++ standard, I was just curious whether in cases where the generated code was what I posted one could assume that that could be atomic etc etc. I also just checked that at least Intel developer manuals very clearly define atomicity with respect to memory operations and not instruction indivisibility, as I assumed: "Locked operations are atomic with respect to all other memory operations and all externally visible events."
C
Community

...and now let's enable optimisations:

f():
        rep ret

OK, let's give it a chance:

void f(int& num)
{
  num = 0;
  num++;
  --num;
  num += 6;
  num -=5;
  --num;
}

result:

f(int&):
        mov     DWORD PTR [rdi], 0
        ret

another observing thread (even ignoring cache synchronisation delays) has no opportunity to observe the individual changes.

compare to:

#include <atomic>

void f(std::atomic<int>& num)
{
  num = 0;
  num++;
  --num;
  num += 6;
  num -=5;
  --num;
}

where the result is:

f(std::atomic<int>&):
        mov     DWORD PTR [rdi], 0
        mfence
        lock add        DWORD PTR [rdi], 1
        lock sub        DWORD PTR [rdi], 1
        lock add        DWORD PTR [rdi], 6
        lock sub        DWORD PTR [rdi], 5
        lock sub        DWORD PTR [rdi], 1
        ret

Now, each modification is:-

observable in another thread, and respectful of similar modifications happening in other threads.

atomicity is not just at the instruction level, it involves the whole pipeline from processor, through the caches, to memory and back.

Further info

Regarding the effect of optimisations of updates of std::atomics.

The c++ standard has the 'as if' rule, by which it is permissible for the compiler to reorder code, and even rewrite code provided that the outcome has the exact same observable effects (including side-effects) as if it had simply executed your code.

The as-if rule is conservative, particularly involving atomics.

consider:

void incdec(int& num) {
    ++num;
    --num;
}

Because there are no mutex locks, atomics or any other constructs that influence inter-thread sequencing, I would argue that the compiler is free to rewrite this function as a NOP, eg:

void incdec(int&) {
    // nada
}

This is because in the c++ memory model, there is no possibility of another thread observing the result of the increment. It would of course be different if num was volatile (might influence hardware behaviour). But in this case, this function will be the only function modifying this memory (otherwise the program is ill-formed).

However, this is a different ball game:

void incdec(std::atomic<int>& num) {
    ++num;
    --num;
}

num is an atomic. Changes to it must be observable to other threads that are watching. Changes those threads themselves make (such as setting the value to 100 in between the increment and decrement) will have very far-reaching effects on the eventual value of num.

Here is a demo:

#include <thread>
#include <atomic>

int main()
{
    for (int iter = 0 ; iter < 20 ; ++iter)
    {
        std::atomic<int> num = { 0 };
        std::thread t1([&] {
            for (int i = 0 ; i < 10000000 ; ++i)
            {
                ++num;
                --num;
            }
        });
        std::thread t2([&] {
            for (int i = 0 ; i < 10000000 ; ++i)
            {
                num = 100;
            }
        });
        
        t2.join();
        t1.join();
        std::cout << num << std::endl;
    }
}

sample output:

99
99
99
99
99
100
99
99
100
100
100
100
99
99
100
99
99
100
100
99

This fails to explain that add dword [rdi], 1 is not atomic (without the lock prefix). The load is atomic, and the store is atomic, but nothing stops another thread from modifying the data between the load and the store. So the store can step on a modification made by another thread. See jfdube.wordpress.com/2011/11/30/understanding-atomic-operations. Also, Jeff Preshing's lock-free articles are extremely good, and he does mention the basic RMW problem in that intro article.
"another observing thread (even ignoring cache synchronisation delays) has no opportunity to observe the individual changes" - is that actually a problem? Even with a std::atomic<int>&, I thought the compiler was free to merge all those operations into one.
What's really going on here is that nobody's implemented this optimization in gcc, because it would be nearly useless and probably more dangerous than helpful. (Principle of least surprise. Maybe someone is expecting a temporary state to be visible sometimes, and are ok with the statistical probabilty. Or they are using hardware watch-points to interrupt on modification.) lock-free code needs to be carefully crafted, so there won't be anything to optimize. It might be useful to look for it and print a warning, to alert the coder that their code might not mean what they think!
That's perhaps a reason for compilers not to implement this (principle of least surprise and so on). Observing that would be possible in practice on real hardware. However, the C++ memory ordering rules don't say anything about any guarantee that one thread's loads mix "evenly" with other thread's ops in the C++ abstract machine. I still think it would be legal, but programmer-hostile.
For the sake of finality, I asked on the std discussion mailing list. This question turned up 2 papers which seem to both concur with Peter, and address concerns that I have about such optimisations: wg21.link/p0062 and wg21.link/n4455 My thanks to Andy who brought these to my attention.
S
Sven Nilsson

The add instruction is not atomic. It references memory, and two processor cores may have different local cache of that memory.

IIRC the atomic variant of the add instruction is called lock xadd


lock xadd implements C++ std::atomic fetch_add, returning the old value. If you don't need that, the compiler will use the normal memory destination instructions with a lock prefix. lock add or lock inc.
add [mem], 1 would still not be atomic on an SMP machine with no cache, see my comments on other answers.
See my answer for a lot more details on exactly how it's not atomic. Also the end of my answer on this related question.
Also, more fundamentally, no, two cores can't have different values in cache for the same memory; caches are coherent. Please don't spread misinformation about how CPUs work. See also, Myths Programmers Believe about CPU Caches (Java volatile is like C++ std::atomic<> with memory_order_seq_cst). See Margaret's answer for how two cores reading the same value leads to a problem.
C
Cody Gray

Since line 5, which corresponds to num++ is one instruction, can we conclude that num++ is atomic in this case?

It is dangerous to draw conclusions based on "reverse engineering" generated assembly. For example, you seem to have compiled your code with optimization disabled, otherwise the compiler would have thrown away that variable or loaded 1 directly to it without invoking operator++. Because the generated assembly may change significantly, based on optimization flags, target CPU, etc., your conclusion is based on sand.

Also, your idea that one assembly instruction means an operation is atomic is wrong as well. This add will not be atomic on multi-CPU systems, even on the x86 architecture.


A
Arne Vogel

Even if your compiler always emitted this as an atomic operation, accessing num from any other thread concurrently would constitute a data race according to the C++11 and C++14 standards and the program would have undefined behavior.

But it is worse than that. First, as has been mentioned, the instruction generated by the compiler when incrementing a variable may depend on the optimization level. Secondly, the compiler may reorder other memory accesses around ++num if num is not atomic, e.g.

int main()
{
  std::unique_ptr<std::vector<int>> vec;
  int ready = 0;
  std::thread t{[&]
    {
       while (!ready);
       // use "vec" here
    });
  vec.reset(new std::vector<int>());
  ++ready;
  t.join();
}

Even if we assume optimistically that ++ready is "atomic", and that the compiler generates the checking loop as needed (as I said, it's UB and therefore the compiler is free to remove it, replace it with an infinite loop, etc.), the compiler might still move the pointer assignment, or even worse the initialization of the vector to a point after the increment operation, causing chaos in the new thread. In practice, I would not be surprised at all if an optimizing compiler removed the ready variable and the checking loop completely, as this does not affect observable behavior under language rules (as opposed to your private hopes).

In fact, at last year's Meeting C++ conference, I've heard from two compiler developers that they very gladly implement optimizations that make naively written multi-threaded programs misbehave, as long as language rules allow it, if even a minor performance improvement is seen in correctly written programs.

Lastly, even if you didn't care about portability, and your compiler was magically nice, the CPU you are using is very likely of a superscalar CISC type and will break down instructions into micro-ops, reorder and/or speculatively execute them, to an extent only limited by synchronizing primitives such as (on Intel) the LOCK prefix or memory fences, in order to maximize operations per second.

To make a long story short, the natural responsibilities of thread-safe programming are:

Your duty is to write code that has well-defined behavior under language rules (and in particular the language standard memory model). Your compiler's duty is to generate machine code which has the same well-defined (observable) behavior under the target architecture's memory model. Your CPU's duty is to execute this code so that the observed behavior is compatible with its own architecture's memory model.

If you want to do it your own way, it might just work in some cases, but understand that the warranty is void, and you will be solely responsible for any unwanted outcomes. :-)

PS: Correctly written example:

int main()
{
  std::unique_ptr<std::vector<int>> vec;
  std::atomic<int> ready{0}; // NOTE the use of the std::atomic template
  std::thread t{[&]
    {
       while (!ready);
       // use "vec" here
    });
  vec.reset(new std::vector<int>());
  ++ready;
  t.join();
}

This is safe because:

The checks of ready cannot be optimized away according to language rules. The ++ready happens-before the check that sees ready as not zero, and other operations cannot be reordered around these operations. This is because ++ready and the check are sequentially consistent, which is another term described in the C++ memory model and that forbids this specific reordering. Therefore the compiler must not reorder the instructions, and must also tell the CPU that it must not e.g. postpone the write to vec to after the increment of ready. Sequentially consistent is the strongest guarantee regarding atomics in the language standard. Lesser (and theoretically cheaper) guarantees are available e.g. via other methods of std::atomic, but these are definitely for experts only, and may not be optimized much by the compiler developers, because they are rarely used.


If the compiler couldn't see all uses of ready, it would probably compile while (!ready); into something more like if(!ready) { while(true); }. Upvoted: a key part of std::atomic is changing the semantics to assume asynchronous modification at any point. Having it be UB normally is what allows compilers to hoist loads and sink stores out of loops.
P
Peter Cordes

On a single-core x86 machine, an add instruction will generally be atomic with respect to other code on the CPU1. An interrupt can't split a single instruction down the middle.

Out-of-order execution is required to preserve the illusion of instructions executing one at a time in order within a single core, so any instruction running on the same CPU will either happen completely before or completely after the add.

Modern x86 systems are multi-core, so the uniprocessor special case doesn't apply.

If one is targeting a small embedded PC and has no plans to move the code to anything else, the atomic nature of the "add" instruction could be exploited. On the other hand, platforms where operations are inherently atomic are becoming more and more scarce.

(This doesn't help you if you're writing in C++, though. Compilers don't have an option to require num++ to compile to a memory-destination add or xadd without a lock prefix. They could choose to load num into a register and store the increment result with a separate instruction, and will likely do that if you use the result.)

Footnote 1: The lock prefix existed even on original 8086 because I/O devices operate concurrently with the CPU; drivers on a single-core system need lock add to atomically increment a value in device memory if the device can also modify it, or with respect to DMA access.


It isn't even generally atomic: Another thread can update the same variable at the same time and only one update is taken over.
Consider a multi-core system. Of course, within one core, the instruction is atomic, but it isn't atomic with respect to the entire system.
@FUZxxl: What were the fourth and fifth words of my answer?
@supercat Your answer is very misleading because it only considers the nowadays rare case of a single core and gives OP a false sense of security. That's why I commented to consider the multi-core case, too.
@FUZxxl: I made an edit to clear up potential confusion for readers who didn't notice that this isn't talking about normal modern multicore CPUs. (And also be more specific about some stuff that supercat wasn't sure of). BTW, everything in this answer is already in mine, except the last sentence about how platforms where read-modify-write is atomic "for free" are rare.
P
Peter Cordes

Back in the day when x86 computers had one CPU, the use of a single instruction ensured that interrupts would not split the read/modify/write and if the memory would not be used as a DMA buffer too, it was atomic in fact (and C++ did not mention threads in the standard, so this wasn’t addressed).

When it was rare to have a dual processor (e.g. dual-socket Pentium Pro) on a customer desktop, I effectively used this to avoid the LOCK prefix on a single-core machine and improve performance.

Today, it would only help against multiple threads that were all set to the same CPU affinity, so the threads you are worried about would only come into play via time slice expiring and running the other thread on the same CPU (core). That is not realistic.

With modern x86/x64 processors, the single instruction is broken up into several micro ops and furthermore the memory reading and writing is buffered. So different threads running on different CPUs will not only see this as non-atomic but may see inconsistent results concerning what it reads from memory and what it assumes other threads have read to that point in time: you need to add memory fences to restore sane behavior.


Interrupts still don't split RMW operations, so they do still synchronize a single thread with signal handlers that run in the same thread. Of course, this only works if the asm uses a single instruction, not separate load/modify/store. C++11 could expose this hardware functionality, but it doesn't (probably because it was only really useful in Uniprocessor kernels to synchronize with interrupt handlers, not in user-space with signal handlers). Also architectures don't have read-modify-write memory-destination instructions. Still, it could just compile like a relaxed atomic RMW on non-x86
Though as I recall, using the Lock prefix wasn't absurdly expensive until the superscalers came along. So there was no reason to notice it as slowing down the important code in a 486, even though it was not needed by that program.
Yes sorry! I didn't actually read carefully. I saw the start of the paragraph with the red herring about decoding to uops, and didn't finish reading to see what you actually said. re: 486: I think I've read that the earliest SMP was some kind of Compaq 386, but its memory-ordering semantics weren't the same as what the x86 ISA currently says. The current x86 manuals may even mention SMP 486. They certainly weren't common even in HPC (Beowulf clusters) until PPro / Athlon XP days, though, I think.
@PeterCordes Ok. Sure, assuming also no DMA/device observers - didn't fit in the comment area to include that one also. Thanks JDługosz for excellent addition (answer as well as comments). Really completed the discussion.
@Leo: One key point that hasn't been mentioned: out-of-order CPUs do reorder things internally, but the golden rule is that for a single core, they preserve the illusion of instructions running one at a time, in order. (And this includes interrupts that trigger context switches). Values might be electrically stored into memory out of order, but the single core that everything is running on keeps track of all the reordering it does itself, to preserve the illusion. This is why you don't need a memory barrier for the asm equivalent of a = 1; b = a; to correctly load the 1 you just stored.
t
tony

No. https://www.youtube.com/watch?v=31g0YE61PLQ (That's just a link to the "No" scene from "The Office")

Do you agree that this would be a possible output for the program:

sample output:

100
100
100
100
100
100
100
100
100
100
100
100
100
100
100
100
100
100
100
100

If so, then the compiler is free to make that the only possible output for the program, in whichever way the compiler wants. ie a main() that just puts out 100s.

This is the "as-if" rule.

And regardless of output, you can think of thread synchronization the same way - if thread A does num++; num--; and thread B reads num repeatedly, then a possible valid interleaving is that thread B never reads between num++ and num--. Since that interleaving is valid, the compiler is free to make that the only possible interleaving. And just remove the incr/decr entirely.

There are some interesting implications here:

while (working())
    progress++;  // atomic, global

(ie imagine some other thread updates a progress bar UI based on progress)

Can the compiler turn this into:

int local = 0;
while (working())
    local++;

progress += local;

probably that is valid. But probably not what the programmer was hoping for :-(

The committee is still working on this stuff. Currently it "works" because compilers don't optimize atomics much. But that is changing.

And even if progress was also volatile, this would still be valid:

int local = 0;
while (working())
    local++;

while (local--)
    progress++;

:-/


This answer seems to only be answering the side-question that Richard and I were pondering. We eventually resolved it: turns out that yes, the C++ standard does allow merging of operations on non-volatile atomic objects, when it doesn't break any other rules. Two standards-discussion documents discuss exactly this (links in Richard's comment), one using the same progress-counter example. So it's a quality-of-implementation issue until C++ standardizes ways to prevent it.
Yeah, my "No" is really a reply to the whole line of reasoning. If the question is just "can num++ be atomic on some compiler/implementation", the answer is sure. For example, a compiler could decide to add lock to every operation. Or some compiler+uniprocessor combination where neither did reordering (ie "the good ol' days") everything is atomic. But what's the point of that? You can't really rely on it. Unless you know that's the system you are writing for. (Even then, better would be that atomic<int> adds no extra ops on that system. So you should still write standard code...)
Note that And just remove the incr/decr entirely. isn't quite right. It's still an acquire and release operation on num. On x86, num++;num-- could compile to just MFENCE, but definitely not nothing. (Unless the compiler's whole-program analysis can prove that nothing sychronizes with that modification of num, and that it doesn't matter if some stores from before that are delayed until after loads from after that.) E.g. if this was an unlock and re-lock-right-away use-case, you still have two separate critical sections (maybe using mo_relaxed), not one big one.
@PeterCordes ah yes, agreed.
D
Damon

Yes, but...

Atomic is not what you meant to say. You're probably asking the wrong thing.

The increment is certainly atomic. Unless the storage is misaligned (and since you left alignment to the compiler, it is not), it is necessarily aligned within a single cache line. Short of special non-caching streaming instructions, each and every write goes through the cache. Complete cache lines are being atomically read and written, never anything different. Smaller-than-cacheline data is, of course, also written atomically (since the surrounding cache line is).

Is it thread-safe?

This is a different question, and there are at least two good reasons to answer with a definite "No!".

First, there is the possibility that another core might have a copy of that cache line in L1 (L2 and upwards is usually shared, but L1 is normally per-core!), and concurrently modifies that value. Of course that happens atomically, too, but now you have two "correct" (correctly, atomically, modified) values -- which one is the truly correct one now? The CPU will sort it out somehow, of course. But the result may not be what you expect.

Second, there is memory ordering, or worded differently happens-before guarantees. The most important thing about atomic instructions is not so much that they are atomic. It's ordering.

You have the possibility of enforcing a guarantee that everything that happens memory-wise is realized in some guaranteed, well-defined order where you have a "happened before" guarantee. This ordering may be as "relaxed" (read as: none at all) or as strict as you need.

For example, you can set a pointer to some block of data (say, the results of some calculation) and then atomically release the "data is ready" flag. Now, whoever acquires this flag will be led into thinking that the pointer is valid. And indeed, it will always be a valid pointer, never anything different. That's because the write to the pointer happened-before the atomic operation.


The load and the store are each atomic separately, but the entire read-modify-write operation as a whole is definitely not atomic. Caches are coherent, so can never hold conflicting copies of the same line (en.wikipedia.org/wiki/MESI_protocol). Another core can't even have a read-only copy while this core has it in the Modified state. What makes it non-atomic is that the core doing the RMW can lose ownership of the cache line between the load and the store.
Also, no, whole cache lines aren't always transferred around atomically. See this answer, where it's experimentally demonstrated that a multi-socket Opteron makes 16B SSE stores non-atomic by transferring cache lines in 8B chunks with hypertransport, even though they are atomic for single-socket CPUs of the same type (because the load/store hardware has a 16B path to L1 cache). x86 only guarantees atomicity for separate loads or stores up to 8B.
Leaving alignment to compiler does not mean that memory will be aligned on 4-byte boundary. Compilers can have options or pragmas to change the alignment boundary. This is useful, for example, for operating on tightly-packed data in network streams.
Sophistries, nothing else. An integer with automatic storage which isn't part of a struct as shown in the example will absolutely positively be correctly aligned. Claiming anything different is just outright silly. Cache lines as well as all PODs are PoT (power-of-two) sized and aligned -- on any non-illusory architecture in the world. Math has it that any properly aligned PoT fits into exactly one (never more) of any other PoT of the same size or larger. My statement is therefore correct.
@Damon, the example given in the question does not mention a struct, but it doesn't narrow the question to just the situations where integers are not parts of structs. PODs most definitely can have PoT size and not be PoT aligned. Take a look at this answer for syntax examples: stackoverflow.com/a/11772340/1219722. So it's hardly a "sophistry" because PODs declared in such way are used in networking code quite a bit in real-life code.
C
Community

That a single compiler's output, on a specific CPU architecture, with optimizations disabled (since gcc doesn't even compile ++ to add when optimizing in a quick&dirty example), seems to imply incrementing this way is atomic doesn't mean this is standard-compliant (you would cause undefined behavior when trying to access num in a thread), and is wrong anyways, because add is not atomic in x86.

Note that atomics (using the lock instruction prefix) are relatively heavy on x86 (see this relevant answer), but still remarkably less than a mutex, which isn't very appropriate in this use-case.

Following results are taken from clang++ 3.8 when compiling with -Os.

Incrementing an int by reference, the "regular" way :

void inc(int& x)
{
    ++x;
}

This compiles into :

inc(int&):
    incl    (%rdi)
    retq

Incrementing an int passed by reference, the atomic way :

#include <atomic>

void inc(std::atomic<int>& x)
{
    ++x;
}

This example, which is not much more complex than the regular way, just gets the lock prefix added to the incl instruction - but caution, as previously stated this is not cheap. Just because assembly looks short doesn't mean it's fast.

inc(std::atomic<int>&):
    lock            incl    (%rdi)
    retq

B
Bonita Montero

When your compiler uses only a single instruction for the increment and your machine is single-threaded, your code is safe. ^^


X
Xirema

Try compiling the same code on a non-x86 machine, and you'll quickly see very different assembly results.

The reason num++ appears to be atomic is because on x86 machines, incrementing a 32-bit integer is, in fact, atomic (assuming no memory retrieval takes place). But this is neither guaranteed by the c++ standard, nor is it likely to be the case on a machine that doesn't use the x86 instruction set. So this code is not cross-platform safe from race conditions.

You also don't have a strong guarantee that this code is safe from Race Conditions even on an x86 architecture, because x86 doesn't set up loads and stores to memory unless specifically instructed to do so. So if multiple threads tried to update this variable simultaneously, they may end up incrementing cached (outdated) values

The reason, then, that we have std::atomic<int> and so on is so that when you're working with an architecture where the atomicity of basic computations is not guaranteed, you have a mechanism that will force the compiler to generate atomic code.


"is because on x86 machines, incrementing a 32-bit integer is, in fact, atomic." can you provide link to documentation that proofs it?
It isn't atomic on x86 either. It's single-core-safe, but if there are multiple cores (and there are) it's not atomic at all.
Is x86 add actually guaranteed atomic? I wouldn't be surprised if register increments were atomic, but that's hardly useful; to make the register increment visible to another thread it needs to be in memory, which would require additional instructions to load and store it, removing the atomicity. My understanding is that this is why the lock prefix exists for instructions; the only useful atomic add applies to dereferenced memory, and uses the lock prefix to ensure the cache line is locked for the duration of the operation.
@Slava @Harold @ShadowRanger I updated the answer. add is atomic, but I made clear that that doesn't imply that the code is race-condition safe, because changes don't become globally visible right away.
@Xirema that makes it "not atomic" by definition though