AtomicSwap instead of AtomicCompareAndSwap?

681 views Asked by At

I know that on MacOSX / PosiX systems, there is atomic-compare-and-swap for C/C++ code via g++.

However, I don't need the compare -- I just want to atomically swap two values. Is there an atomic swap operation available? [Everythign I can find is atomic_compare_and_swap ... and I just want to do the swap, without comparing].

Thanks!

3

There are 3 answers

0
PinkyNoBrain On BEST ANSWER

the "lock xchg" intel assembly instruction probably achieves what you want but i dont think there is a GCC wrapper function to make it portable. Therefor your stuck using inline assembly(not portable) or using compare and swap and forcing the compare to be true(inneficient). Hope this helps :-)

0
Jack Lloyd On

GCC does provide this operation on some processors, under the (confusingly named) __sync_lock_test_and_set. From the GCC documentation:

 This builtin, as described by Intel, is not a traditional
 test-and-set operation, but rather an atomic exchange operation.
 It writes VALUE into `*PTR', and returns the previous contents of
 `*PTR'.

 Many targets have only minimal support for such locks, and do not
 support a full exchange operation.  In this case, a target may
 support reduced functionality here by which the _only_ valid value
 to store is the immediate constant 1.  The exact value actually
 stored in `*PTR' is implementation defined.

However the full swap operation is supported on x86-32 and x86-64, effectively providing the lock xchg wrapper you would otherwise need to write.