Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do xchg assembly instruction in c++ coding atomically

Tags:

c++

c

assembly

I want to implement TestandSet atomically in c++. what operation is equivalent to xchg instruction in c++

like image 466
user2058173 Avatar asked Dec 31 '25 14:12

user2058173


2 Answers

You can use intrinsics functions, depending on your compiler. In gcc for e.g. use __sync_lock_test_and_set (see - http://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Atomic-Builtins.html)

Alternatively you can use inline assembly and do the locked xchg directly

If you're working in c++11 you can use std::atomic functions. This however provides a higher level of abstraction so the translation to x86 ISA is not one-to-one. See - https://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html

like image 67
Leeor Avatar answered Jan 02 '26 06:01

Leeor


On Windows - InterlockedCompareExchange().

In GCC - __sync_bool_compare_and_swap().

like image 24
Seva Alekseyev Avatar answered Jan 02 '26 06:01

Seva Alekseyev