The C++ Standard Library has both free functions and member functions for atomic compare and swap operations.
As noted for free functions:
These functions are defined in terms of member functions of std::atomic:
- obj->compare_exchange_weak(*expected, desired)
- obj->compare_exchange_strong(*expected, desired)
- obj->compare_exchange_weak(*expected, desired, succ, fail)
- obj->compare_exchange_strong(*expected, desired, succ, fail)
What is the reason for having free functions? Wouldn't it be enough to have member functions only? Don't they do the same thing?
Implementation in C Many C compilers support using compare-and-swap either with the C11 <stdatomic. h> functions, or some non-standard C extension of that particular C compiler, or by calling a function written directly in assembly language using the compare-and-swap instruction.
test-and-set modifies the contents of a memory location and returns its old value as a single atomic operation. compare-and-swap atomically compares the contents of a memory location to a given value and, only if they are the same, modifies the contents of that memory location to a given new value.
Consistency with the C stdatomic.h
operations.
If you use the free functions, the same atomics-manipulating code will work in both C and C++, with only a typedef needing to be conditionally defined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With