Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do both free and member functions exist for compare and swap operations?

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:

  1. obj->compare_exchange_weak(*expected, desired)
  2. obj->compare_exchange_strong(*expected, desired)
  3. obj->compare_exchange_weak(*expected, desired, succ, fail)
  4. 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?

like image 770
ks1322 Avatar asked Jan 21 '18 15:01

ks1322


People also ask

How to use compare-and-swap in C?

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.

Why is compare-and-swap better than test and set?

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.


1 Answers

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.

like image 138
Ben Voigt Avatar answered Sep 30 '22 12:09

Ben Voigt