Is this a correct implementation for a generic atomic swap function? I'm looking for a C++03-compatible solution on GCC.
template<typename T>
void atomic_swap(T & a, T & b) {
static_assert(sizeof(T) <= sizeof(void*), "Maximum size type exceeded.");
T * ptr = &a;
b =__sync_lock_test_and_set(ptr, b);
__sync_lock_release(&ptr);
}
If not, what should I do to fix it?
Also: is the __sync_lock_release
always necessary? When searching through other codebases I found that this is often not called. Without the release call my code looks like this:
template<typename T>
void atomic_swap(T & a, T & b) {
static_assert(sizeof(T) <= sizeof(void*), "Maximum size type exceeded.");
b = __sync_lock_test_and_set(&a, b);
}
PS: Atomic swap in GNU C++ is a similar question but it doesn't answer my question because the provided answer requires C++11's std::atomic
and it has signature Data *swap_data(Data *new_data)
which doesn't seem to make sense at all for a swap
function. (It actually swaps the provided argument with a global variable that was defined before the function.)