Can we use Compare-and-Swap operation on non-atomic variable?

67 views Asked by At

Hi I noticed that the CAS Compare-and-Swap operations are usually operated on atomic variables, see https://en.cppreference.com/w/cpp/atomic/atomic/compare_exchange, https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicLong.html#compareAndSet-long-long-, and https://en.cppreference.com/w/cpp/atomic/atomic_compare_exchange.

Can we use CAS operations on normal variables? for example, I have an array of bytes, can I just pick the array[11] and do CAS operation on it?

1

There are 1 answers

0
Peter Cordes On

Yes, as long as any other unsynchronized accesses in other threads are also atomic. e.g. in C++20 with std::atomic_ref, or in GNU C with __atomic_compare_exchange_n https://gcc.gnu.org/onlinedocs/gcc/_005f_005fatomic-Builtins.html.

Atomicity is a property of an access, not of the chunk of bytes, but most languages expose that to programmers by providing "atomic types" where every access is atomic.