Implementing ABA Counter with C 11 CAS
The ABA problem occurs when a memory location's value is modified twice, with an intervening modification that sets it back to its original value. This can trick a thread relying on atomic compare-and-swap (CAS) operations into believing that a value has not changed, when in fact it has.
To prevent the ABA problem, a common solution is to create a counter that increments with each change to the memory location. This counter is incremented atomically along with the change, so that the CAS operation can check if the counter has also changed since the last operation.
In C 11, the std::atomic_compare_exchange_weak function provides an atomic CAS operation. However, it does not allow for the simultaneous modification of multiple variables, such as the value and the counter.
To implement an ABA counter with C 11 CAS, we need to store the counter and the value in adjacent memory locations, so that a single CAS operation can update both values atomically. This can be achieved using a struct with two members, where the first member is the value and the second member is the counter:
struct Node { std::atomic<int> value; std::atomic<int> counter; };
With this data structure, we can use the std::atomic_compare_exchange_weak function to implement the ABA counter:
void modifyValue(Node& node, int newValue) { int expectedValue = node.value.load(std::memory_order_relaxed); int expectedCounter = node.counter.load(std::memory_order_relaxed); bool success; do { success = node.value.compare_exchange_weak(expectedValue, newValue, std::memory_order_acq_rel); success = node.counter.compare_exchange_weak(expectedCounter, expectedCounter + 1, std::memory_order_acq_rel); } while (!success); }
In this example, the modifyValue function first loads the expected value and counter using the std::memory_order_relaxed memory order, which allows for the values to be read out of order and can lead to tearing.
The std::atomic_compare_exchange_weak function is then used to compare the expected value and counter with the current values in the memory location. If the values match, the new value and counter are written to the location using the std::memory_order_acq_rel memory order, which ensures that the write is visible to other threads after the operation completes.
If the values do not match, the compare_exchange_weak function fails and the loop is executed again, loading the latest expected value and counter before attempting the atomic exchange again.
This implementation ensures that the counter is incremented atomically with the value, preventing the ABA problem and ensuring that threads can safely rely on the value's consistency.
The above is the detailed content of How to Implement an ABA Counter in C 11 Using Atomic Compare-and-Swap?. For more information, please follow other related articles on the PHP Chinese website!