Question

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!

Was it helpful?

Solution

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 :-)

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top