Thursday, April 10, 2014

On std::atomic_compare_exchange_*

When I started using the new atomic_compare_exchange_*() functions available on C++11 I struggled a bit to get it right. It seems I wasn't the only one, because other people are complaining that the API is broken... which according to Herb Sutter is not true and he has a post explaining why:

After an afternoon of banging my head against the wall, I figured out how to use these functions and got the implementation right for the data structure I was trying to port from Java to C++11.

I was mislead by Java's atomics APIs because in Java Atomics classes, there is a compareAndSet(), while the C++11 it is an atomic_compare_exchange_*(). I blame myself for it though, because the names really say it all: one is a set, while the other is an exchange.
The C++11 API does an exchange of the variables, while the Java just sets the variable to the new value.

Yep, it's as simple as that, and I wasted an afternoon on it, which I know, was a dumb mistake, but I guess those are the easier ones to do  ;)

No comments:

Post a Comment