The hypothetical program fragment already contains the required operation, but the error still remains. The thread reads the shared counter, calculated the next value, and tries to store it via compare-and-exchange. If it fails, the loop repeats the command. At first glance, repetition should correct the race: the comparison is atomic. But the next attempt uses the result calculated from the previous observation. The processor accurately performs the task and thereby preserves the author’s mistake. It is useful to start a review from the place of calculation, and not from the promises of the word atomic itself.
Let’s imagine a counter without overflow in the considered interval. You need to increase it by one for each successful request. In the first version, expected is read once, desired is also calculated once, and inside only compare_exchange_weak is repeated. Let thread A see 10 and prepare 11. While it was preparing, B successfully set 11. Attempt A fails the comparison, but expected receives the value observed in this attempt, 11. If desired remains the same, the next successful attempt writes 11 instead of 12. Two intentions to increase the counter resulted in one increase.
This is a hypothetical execution schedule, not an editorial test result. It is needed to check data dependency. The success of the second command only means that its condition matched the current representation of the value. The instruction knows nothing about the human intention of “one more increase.” To express that intention, the new desired must arise from the new expected. The error appeared between two atomic operations, in a normal calculation, which the author mistakenly removed from the loop.
Mark next to mutable expected
For a simple unsigned counter, the corrected form might look like this. Here, all accesses to a common object are atomic; publication of other data is not included in the task.
unsigned expected = counter.load(std::memory_order_relaxed);
for (;;) {
unsigned desired = expected + 1;
if (counter.compare_exchange_weak(expected, desired,
std::memory_order_relaxed,
std::memory_order_relaxed))
break;
}
The note in the margin refers to the desired line: it is re-executed after failure. The updated expected is the input to the next calculation. The C++ working draft describes this semantics explicitly: if there is a mismatch in expected, the value observed during the atomic comparison is returned. Expected here is not a constant reference, but a mutable repetition protocol variable. It is easy to read its name too literally and miss this property.
You should not explain the example by saying “if it fails, the operation does nothing.” For the shared counter, the desired replacement does not occur, but the local expected may change. The return boolean value and the argument change report different parts of the result. In another library, the interface may return the previous value directly. This is how Microsoft _InterlockedCompareExchange works: the result of the function must be compared with comparand. Moving a loop between interfaces requires moving their contract, not just the familiar name.
Desired doesn’t have to be an increase either. The program can set a bit, replace the status field, and combine flags. If the new value depends on the old value read, the dependence must be recalculated after each new observation. If the operation really requires setting one constant for one specific state, the recalculation may be meaningless. The shape of the loop is determined by the operation on the data. One corrected counter does not provide a required template for every concurrent data structure.
For an unsigned type, addition is defined modulo its range. However, the application counter is not necessarily allowed to reset to zero after the maximum. Our original constraint eliminated overflow precisely to avoid hiding yet another contract behind the syntax. A saturating counter would require another calculation of desired and a decision on the result when the limit is reached. Atomicity does not make unbounded-range mathematical addition a finite-register property. The semantics of the number are chosen before discussing possible instruction speedup.
A note beside the machine instruction
On x86, the corresponding machine operation is often CMPXCHG with a LOCK prefix for the shared memory operand. The architectural description is in Intel Software Developer Manuals. The C++ connection cannot be made into a universal identity: compiler, type, alignment, target architecture, and supported atomic widths affect the implementation. For some objects, the library may require a different sequence or locking. Checking a specific build answers a separate question about what is actually running.
CMPXCHG compares the accumulator to the destination operand. In case of equality, the proposed new value is written; in case of inequality, the accumulator receives the observed value of the destination operand. The ZF flag reports the outcome of the comparison. This allows you to see the relationship with the mutable expected, but the register and the language argument remain different levels of description. A C++ program must follow the rules of the language, even on a machine where the author knows well the one appropriate instruction. Ordinary non-atomic accesses from a neighboring thread do not become valid when an assembly instruction appears somewhere nearby.
The LOCK prefix ensures the desired indivisibility of the corresponding memory operation relative to competing operations. Its name does not mean that the entire machine must be stopped for the entire duration of the variable’s existence. A modern implementation uses the architecture’s coherence mechanisms; the particular path depends on the location and properties of the memory. Therefore, the promise of “one instruction is always cheap” is as unfounded as describing it as a global pause. The number of instructions does not measure the cost of obtaining shared mutable state.
This price is especially noticeable when there are many participants trying to update one object. They can repeatedly lose the already prepared desired and repeat the calculation. A successful write by one participant renders some of the others’ work useless. No measured nanoseconds are required for this explanation: the consequence follows from the contention schedule itself. But you can estimate the real time loss, compare the algorithm with mutex, or select the delay between attempts only for a specific load. Such an experiment was not carried out here and no measured speedup is claimed.
Weak allows spurious failure: the compared representations can match and the operation will still return false. That is why the portable loop must correctly survive another attempt without necessarily proving the intervention of a neighbor. Strong eliminates this kind of spurious failure, but does not promise that the value will not be changed by another thread. The word strong does not strengthen the operation to ensure success, nor does it make every data structure lock-free. This is a characteristic of a specific comparison contract, and not an assessment of the quality of the entire program.

The following note applies to the body of the function being recalculated. If, along with desired, it sends a message, writes off an application resource, or modifies an external object, failed attempts may execute the side effect multiple times. The replacement of the counter remains atomic; the adjacent action is not rolled back automatically. Well-designed repetition separates the candidate’s preparation from the action, which must happen once. Sometimes this requires a different protocol entirely. CMPXCHG cannot be tasked with undoing effects that the instruction has never seen or controlled.
Equality after return
Now let’s change the problem. The shared value was A, then another participant set B, and later A again. When the deferred comparison is resumed, the expected A is the same as the current A. The replacement can legally pass. In a regular counter, this sometimes does not create a separate problem: only an operation on the current number is required. But if A represents the address of a node, previous assumptions about the contents of the node and its connections may no longer apply. A value match does not preserve the object’s biography.
This gives rise to a family of problems known as ABA. The name describes the observed return, but the specific invariant violated is important. In the hypothetical structure, the node at address A could be removed, its memory used differently, and the same address could later be reused. The old thread can compare the address successfully, even though its continued computation relied on the previous owner of that memory. To prove an error, you need to show which stored assumption became false. One sequence of letters does not prove that any compare-and-exchange algorithm is defective.
Here they often suggest adding a generation number. Then the address and version are compared together, and the return of one address with the new version is no longer equal to the old pair. This is a useful idea with significant premises. The pair must be updated indivisibly with the required width, the version counter must not unnoticed go full circle in a dangerous interval, and all participants must follow the same protocol. A separate address write and a separate version write destroy the original proof. The presence of two fields does not mean that the pair can be updated atomically.
In addition, the generation mark itself does not give the right to dereference already freed memory. Protecting the lifetime requires a mechanism of its own: for example, a suitable delayed release protocol. It is possible to successfully detect the replacement after reading and still access the invalid object too early. Therefore, ABA prevention and permission to access the node must be checked together. The article deliberately does not contain a ready-made recipe for a concurrent stack: such a recipe without a full breakdown of memory ownership would be a dangerously incomplete technical explanation.
It is useful to return to the first counter and notice that the memory order there was deliberately chosen as relaxed. We only wanted an indivisible change in the number itself and excluded the publication of other objects. If a successful operation transfers ownership of the data to another thread, additional ordering relationships will be needed. Replacing relaxed with seq_cst will not fix the obsolete desired and will not resurrect the freed node. The stronger order does not restore the missing dependency and does not record the history that the value representation does not contain at all.
Even a correct loop does not promise fairness. An individual participant can keep losing update attempts to others. The progress properties of the algorithm require their own proof and depend on the implementation of the atomic type and the surrounding code. Lock-free and wait-free describe different guarantees; none can be inferred solely from the absence of the word mutex in the short listing. For choosing a solution, the limitation of participant delay, the cost of repetitions, and the ease of checking the lifetime are important. Sometimes more explicit ownership gives the system a more useful property than a spectacularly short machine path.
Comparison also depends on the value representation. For a chosen simple integer, the expected interpretation is clear. For an arbitrary type, you cannot automatically replace the compare-and-exchange contract with a regular equality operator. The C++ working text talks about value representation; in particular, the bitwise representation of floating-point numbers requires special care. If the author is assembling a composite atomic object, he should examine the requirements for the type and supported implementation, rather than transfer the integer-counter proof merely because the code looks similar. Otherwise, the condition for successful replacement may differ from the application’s concept of “this is the same object.” Verifying this consistency is a matter of data design, even before analyzing the thread schedule.
Sources verified November 2, 2026. This is an explanation of a long-standing CPU operation, not a message about a new instruction set. The corrected loop now calculates desired from the expected value relevant to that attempt; it was precisely this dependence that was required by the original problem. If the program needs more history of the object, it will have to represent and protect this history separately. The processor will compare exactly what was given to it. The last note in the review is next to the data that the author has not yet included in the comparison.



