Question

Global:

std::atomic<T*> a, b;

In thread A:

// this like std::swap(a, b), but is it atomic?
a.exchange(b.exchange(a));

In thread B:

T* p = a.load();
doSomethine(p);
Was it helpful?

Solution

Sequences of atomic operations aren't atomic. Something could happen between b.exchange and a.exchange, and observe that both a and b have the same value (the original value of a).

If you don't want this, use some type of lock.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top