Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to atomically load and store on X86 processors?

Can this be done atomically?

void load_and_store(int* dst, int* src) {
  int data = *src;
  *dst = data;
}

If atomic store has to be done with XCHG [addr], EAX, I would have to load the data into EAX first. Then load and store are not atomic.

gcc atomic extension has void __atomic_store (type *ptr, type *val, int memmodel) which looks like being able to do both load and store atomically.

like image 410
woodings Avatar asked Oct 29 '25 12:10

woodings


1 Answers

I do not believe there is any instruction on x86 that atomically does both a load and a store, to different addresses. (I'm not sure about other architectures, but I doubt there are very many, if any, that do. It serves no useful value and would be expensive.)

x86 (and x86_64) have a number of instructions that can be made to do atomic read-modify-write operations but only to a single memory location. For example BTS does test-and-set. XCHG exchanges the value in a register with the value in a memory location. XADD does an atomic increment. CMPXCHG does a compare-and-swap. None of these are atomic by default, but can be made atomic by adding the LOCK prefix to the assembly instruction.

The gnu __atomic_store(type *ptr, type *val, int memmodel) does not do what you think it does. See http://gcc.gnu.org/onlinedocs/gcc/_005f_005fatomic-Builtins.html. What it does is load val into a register (or something (it's actually not defined what it does with val)) and then atomically stores the value into the memory location given by ptr.

On x86 aligned loads and stores (for values 32-bits and less) are atomic by default.

But you shouldn't be using the gnu builtins unless you have to. Instead use the --std=c++11 flag, and then use the C++ atomics.

like image 122
Wandering Logic Avatar answered Nov 01 '25 02:11

Wandering Logic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!