Guillaume Paris
Guillaume Paris

Reputation: 10519

atomic exchange vs compare_exchange_xxx

bool expected = false;
extern std::atomic<bool> current; // set somewhere else
while (!current.compare_exchange_weak(expected, true)
       && !expected);

What is the need to use this code versus current.exchange(expected) ?

Does exchange can induce some race condition ?

edited: same question versus current.store(expected)

Upvotes: 2

Views: 616

Answers (1)

Aaron Altman
Aaron Altman

Reputation: 1755

exchange and compare_exchange_weak have different semantics in general, but in your example it doesn't look like you're relying on any behavior that would demonstrate that. If you have two or more threads that are racing to write the same value, it doesn't matter who gets there first, and in fact you don't even need the protection of std::atomic. To understand the differences, you'd have to look at an example where the behavior of a given thread would depend on what had happened before it arrived at the point of calling exchange or compare_exchange_weak.

Upvotes: 1

Related Questions