uint32_t fetch_multiply(std::atomic<uint32_t>& shared, uint32_t multiplier)
{
uint32_t oldValue = shared.load();
while (!shared.compare_exchange_weak(oldValue, oldValue * multiplier))
{
}
return oldValue;
}
If shared.compare_exchange_weak() fails because of a concurrent writer, then the while loop will never exit (unless another writer sets the value of shared to oldValue).What the author wants is something like this:
uint32_t fetch_multiply(std::atomic<uint32_t>& shared, uint32_t multiplier)
{
while(1) {
uint32_t oldValue = shared.load();
if(shared.compare_exchange_weak(oldValue, oldValue * multiplier)) {
return oldValue;
}
}
}
The other examples have the same problem.