**无锁编程在不使用互斥量的情况下协调线程,使用原子的 compare-and-swap(CAS)循环,使得即便其他线程停滞,至少总有一个线程能取得进展。**没有线程会因另一个线程持有锁而被阻塞。
CAS
Compare-and-swap 只有在某个位置仍持有预期的旧值时,才原子地把它设为新值;否则失败并让你重试。它是无锁栈、队列和计数器背后的原语。
text
CAS(addr, expected, new):
if *addr == expected: *addr = new; return true # 原子的,不可分割
else: return false
java
// 通过 CAS 重试循环实现无锁自增
int old, next;
do {
old = value.get();
next = old + 1;
} while (!value.compareAndSet(old, next)); // 如果别人抢先了就重试
