Can anyone give me a summary of the advantages and disadvantages of Compare And Swap programming ? (e.g. multi-core CPU performance)
Here's and example in Java:
/**
* Atomically increments by one the current value.
*
* @return the updated value
*/
public final int incrementAndGet() {
for (;;) {
int current = get();
int next = current + 1;
if (compareAndSet(current, next))
return next;
}
}
=== EDIT===
Please talk about this specially in single/core CPUs.
Advantage: no locks, hence no deadlock and generally better scalability
Disadvantage: risk of starvation (unless the algorithm is also wait-free, but this is generally not the case)
edit:wait-free algorithms do some operations when it losses CAS race.instead of busytrying/startvation.