读书笔记: 多处理器编程的艺术
https://book.douban.com/people/fleure/annotation/21334175/
Spin Locks and Contention
<原文开始>
the TASLock performs very poorly, and the TTASLock performance, while substantially better, still falls far short of the ideal.
</原文结束>
TASLock: Test And Set Lock
TTASLock: Test and Test And Set Lock,相比 TAS ,增加了一个 double check:
<代码开始 lang="java">
public class TTASLock Implements Lock {
AtomicBoolean state = new AtomicBoolean(false);
public void lock() {
while (true) {
while (state.get()) {} ;
if (! state.getAndSet(true)) {
return ;
}
}
}
public void unlock() {
state.set(false);
}
}
</代码结束>
<原文开始>Now consider the behavior of the TTASLock algorithm while the lock is held by a thread A. The first time thread B reads the lock it takes a cache miss, forcing B to block while the value is loaded into B's cache. As long as A holds the lock, B repeatly reread the value, but hits in the cache every time. </原文结束>
TTASLock 比 TASLock 优良在于更多地读取本地缓存,而不是每次都锁总线。
<原文开始>This notion of local spinning, where threads repeatly reread cached values instead of repeatedly using the bus, is an important principle critical to the design of efficeient spin locks.</原文结束>
<原文开始>Here is a key observation: if some other thread aquires the lock between hte first and second step, then, most likely, there is high conteniton for that lock.</原文结束>
<原文开始>the larger the number of unsuccessful tries, the higher the likely contention, and the longer the thread should back off .</原文结束>
<原文开始>backing off is common to several locking algorithms.</原文结束>
<原文开始>the BackoffLock is easy to implement, and typically performs significantly better than TASLock on many architectures. </原文结束>
如果 double check 第一步失败了,那么它很有可能是在高的 contention,那么在这里退避是一条简单易行的优化路线;contention 越高,退避的时间可以越长。
原文开始>原文开始>原文开始>原文开始>原文开始>原文开始>代码开始>原文开始>