How to implement CAS in C ++ 11

I want to know how to implement compare_and_swap in C ++ 11. Here is what I tried:

template<typename T> T compare_and_swap(atomic<T>& reg,T newVal ) { bool success = false; T oldVal; do { oldVal = reg.load(); success = reg.compare_exchange_weak(oldVal,newVal); }while(!success); return oldVal; } 

Is there a better way to implement this?

+5
source share
1 answer

Here's how I do it:

 //untested code template<typename T> T compare_and_swap(atomic<T>& reg,T newVal ) { oldVal = atomic_load(reg); while(!atomic_compare_exchange_weak(&reg, &oldVal, newVal)); return oldVal; } 

The exchange comparison function will update the oldval value if it is not executed. Therefore, there is no need to repeat this.

As you can see, I prefer to use explicit atomic operations. This is due to the fact that they are not always implemented. As explained by Herb Sutter here (the rest of the video may also interest you :)).

As an unnecessarily superfluous thought, I would like to warn against using this function with the help of types trivially copied . Or "normal" pointers. General pointers are generally ok :).

0
source

All Articles