Load value from memory, increment it locally, use compare and swap on (address, old value, incremented value), compare to original value, and if they're the same then we're good.
If someone else accessed after we loaded the value before, then the values won't be the same so we won't swap (increment).
This comment was marked helpful 0 times.
jpaulson
atomicIncrement(int* x) {
while(true) {
int n = *x;
if(CAS(x, n, n+1) == n) break;
}
}
This comment was marked helpful 0 times.
sfackler
Atomic addition is so common that many architectures provide specialized instructions for it. For example, x86 provides xadd, which when combined with the lock prefix, performs addition atomically.
This comment was marked helpful 0 times.
bottie
int atomicIncrement (int* addr) {
int old = *addr;
int assumed;
do {
assumed = old;
old = atomicCAS(addr, assumed, assumed+1);
} while (old != assumed)
return old;
}
Load value from memory, increment it locally, use compare and swap on (address, old value, incremented value), compare to original value, and if they're the same then we're good.
If someone else accessed after we loaded the value before, then the values won't be the same so we won't swap (increment).
This comment was marked helpful 0 times.
This comment was marked helpful 0 times.
Atomic addition is so common that many architectures provide specialized instructions for it. For example, x86 provides
xadd
, which when combined with thelock
prefix, performs addition atomically.This comment was marked helpful 0 times.
This comment was marked helpful 0 times.