简单介绍
锁的一些问题
什么样的程序是无锁编程?
Thread-safe access to shared data without the use of synchronization primitives such as mutexes. It is possible but not practical in the absence of hardware support
- 有多个threads(线程或进程)
- 访问共享区域
- threads之间不能block彼此
Designing generalized lock-free algorithms is hard. Design lock-free data structures instead: buffer, list, stack, queue, map, deque, snapshot
ABA问题
Thread 1 基于变量x=A的基础上做了一系列操作,然而Thread 2将x改为了B。 如果Thread 1进行compare-and-set的话,会发现x已改变,撤回其进行的一系列操作。但是在这之前Thread 2又将变量变回了A!这导致Thread 1在x=B的情况下进行了一系列不合法的操作!
CMU的PDF有点抽象啊!!!
CAS(Compare and swap)
链接1
链接2
先比较输入的当前值和内存中的值是否一致,不一致则代表内存数据发生了变化,CAS失败。
就是防止在 读-计算-写 的这个过程中,原本读的值在写之前被改变。
CAS is an atomic operation, which means that fetch and update together are one single operation:
The important thing here is that CAS does not acquire a lock on the data structure but returns true if the update was successful, otherwise it returns false. The hardware should support compare-and-swap, to make it a truly atomic operation without the use of locking.
How CAS can be called:
void testCas() {
int v = value;
int x = v + 1;
while(!cas(v, x)) {
v = value;
x = v + 1;
}
}
Load-link/store-conditional
Fetch and Add
Non-Blocking Queue
就是用CAS基础做判断。
Wait-Free Queue
java中使用free lock: java.util.concurrent package
这个类超级大 非常不妙啊