无锁方案 CAS
无锁方案高效的核心是 CPU 提供了 CAS(Compare And Swap,即“比较并交换”) 指令,由硬件直接支持,CAS 是一个原子指令。
CAS Wiki 中有说明 CAS 是用于多线程中获取同步的原子指令,可以表示成以下形式:
func cas(p : pointer to int, old : int, new : int) returns bool {
if *p != old {
return false
}
*p = new
return true
}如果利用 cas 来实现增加操作:
function add(p : pointer to int, a : int) returns int {
done = false
// 这个是经典范式,自旋操作
while not done {
value = *p // Even this operation doesn't need to be atomic.
done = cas(p, value, value + a)
}
return value + a
}使用 CAS 需要注意 ABA 问题。
原子类
Java 中的 JUC 提供了很多的原子类,如 AtomicLong.
利用 CAS 来实现单例模式
单例模式的实现方式有很多种方式,大部分实现利用的是锁机制,如 synchronized,使用无锁方案也可以实现单例模式
Disruptor 中的无锁算法
Disruptor 是一个高性能的有界内存队列,其中入队的操作采用了无锁算法
最后更新于
这有帮助吗?