1

AtomicInteger in Java is implemented using volatile and CAS mechanism. source code

But, how C++11 implement atomic?

expoter
  • 1,622
  • 17
  • 34
  • The implementation of atomic types in Java is not written in Java - it is based on what happens in the JVM (which interprets the bytecode, and takes action on the host system). Similarly, in C++, the implementation of atomic types depends on the implementation (i.e. the specifics of how the compiler and standard library do things for the target machine). – Peter Aug 23 '21 at 09:15

4 Answers4

3

std::atomic is part of the C++ language; on ISAs that support atomic instructions it directly translates to those instructions. On x86 for example there's the LOCK prefix that can be used with loads and stores, as well as the LOCK CMPXCHG (the "CAS" instruction).

In addition to CPU instructions, std::atomic affects the memory order semantics of the program. For more details refer to C++ atomics and memory ordering and the C++ memory model.

On an ISA lacking atomic instructions the compiler is allowed to implement it using helper routines/locks, in which case is_lock_free() could return false (this is unlikely to happen for primitive types as all SMP systems support atomic operations natively).

rustyx
  • 80,671
  • 25
  • 200
  • 267
1

if it's possible std::atomic will use a native assembly level instruction that will atomically assign a value. if it's not possible (whether it's because you're using a non-native datatype or because the cpu doesn't support such an instruction) it will default to using an std::lock to ensure the access to it is safe (so not actually atomic at that point)

AntiMatterDynamite
  • 1,495
  • 7
  • 17
1

volatile in C++ means not the same as in Java, in C++ it does not imply memory ordering.

Atomics are implemented using compiler extensions (intrinsics/builtin functions).

Alex Guteniev
  • 12,039
  • 2
  • 34
  • 79
0

I've found something inside the atomic header source which redirects to this page. Then you'll see the index with Implementation and, under that and many other things, there is Integers.

R1D3R175
  • 92
  • 7