Swapping two unique_ptrs is not guaranteed to be threadsafe.
std::unique_ptr<T> a, b;
std::swap(a, b); // not threadsafe
Since I need atomic pointer swaps and since I like the ownership handling of unique_ptr, is there a simple way to combine them both?
Edit: If this is not possible, I am open for alternatives. I at least want to do something like this:
threadshared_unique_ptr<T> global;
void f() {
threadlocal_unique_ptr<T> local(new T(...));
local.swap_content(global); // atomically for global
}
What is the idiomatic way of doing this in C++11?
Lock-free swapping of two pointers
It seems there is no general lock-free solution for this problem. To do this, you need a possibility to atomically write new values into two non-continous memory locations. This is called
DCAS, but it is not available in Intel processors.Lock-free transfer of ownership
This one is possible, as it is only needed to atomically save new value into
globaland receive its old value. My first idea was to useCASoperation. Take a look at the following code to get an idea:Steps
globalpointer intemplocaltoglobalifglobalis still equal totemp(it wasn't changed by other thread). Try again if this is not true.Actually,
CASis overkill there, as we do not do anything special with oldglobalvalue before it is changed. So, we just can use atomic exchange operation:See Jonathan's answer for even more short and elegant solution.
Anyway, you will have to write your own smart pointer. You can't use this trick with standard
unique_ptr.