Relative performance of swap vs compare-and-swap locks on x86

I assume atomic_swap(lockaddr, 1) gets translated to a xchg reg,mem instruction and atomic_compare_and_swap(lockaddr, 0, val) gets translated to a cmpxchg[8b|16b]. Some linux kernel developers think cmpxchg ist faster, because the lock prefix isn’t implied as with xchg. So if you are on a uniprocessor, multithread or can otherwise make sure the lock isn’t needed, you … Read more

What is the difference between std::shared_ptr and std::atomic aka. std::experimental::atomic_shared_ptr?

The atomic “thing” in shared_ptr is not the shared pointer itself, but the control block it points to. meaning that as long as you don’t mutate the shared_ptr across multiple threads, you are ok. do note that copying a shared_ptr only mutates the control block, and not the shared_ptr itself. std::shared_ptr<int> ptr = std::make_shared<int>(4); for … Read more

Why is there no overload of Interlocked.Add that accepts Doubles as parameters?

Others have addressed the “why?”. It is easy however to roll your own Add(ref double, double), using the CompareExchange primitive: public static double Add(ref double location1, double value) { double newCurrentValue = location1; // non-volatile read, so may be stale while (true) { double currentValue = newCurrentValue; double newValue = currentValue + value; newCurrentValue = … Read more

C++ std::atomic vs. Boost atomic

I’m not an expert or anything, but here’s what I know: std::atomic simply says that calling load and store (and a few other operations) concurrently is well-defined. An atomic operation is indivisible – nothing can happen ‘in-between’. I assume std::atomic is based off of boost::atomic. If you can, use std, otherwise use boost. They are … Read more

Why isn’t atomic double fully implemented

std::atomic<double> is supported in the sense that you can create one in your program and it will work under the rules of C++11. You can perform loads and stores with it and do compare-exchange and the like. The standard specifies that arithmetic operations (+, *, +=, &, etc.) are only provided for atomics of “integral … Read more

what is “failure atomicity” used by J bloch and how its beneficial in terms of immutable object?

Bloch’s “Failure atomicity” means that if a method threw an exception, the object should still be usable afterwards. Generally, the object should be in the same state as it was before invoking the method. In the case of an immutable object, you gain that simply from the fact that it’s immutable. There is no operation … Read more

Can atomics suffer spurious stores?

Your code makes use of fetch_add() on the atomic, which gives the following guarantee: Atomically replaces the current value with the result of arithmetic addition of the value and arg. The operation is read-modify-write operation. Memory is affected according to the value of order. The semantics are crystal clear: before the operation it’s m, after … Read more