4. FIFO ticket spinlock (solved the fairness problem) TTAS with random backoff还有一个公平性的问题,当锁释放时,谁能抢到锁是随机的。并不是等待 最久的那个竞争者会得到锁。这样就可能造成一个thread会busy looping很长的时间而得不到锁。
Linux kernel x86的ticket spinlock是有Nick Piggin实现的,在2.6.25中被接受。 (git commit id is: 314cdbefd1fd0a7acf3780e9628465b77ea6a836)
1. 初始化 -> slock: owner = next = 0 2. CPU0第一个拿到了锁 -> slock: owner = 0, next = 1 3. 当CPU1也想竞争这把锁的时候,xaddw -> slock: owner = 0, next = 2 同时 inc: owner = 0, next = 1 它发现inc: owner != next (注意它是在测试inc这个变量),就等待(rep; nop),然后把s lock的owner读入inc。如果CPU0释放了锁,它会把slock:owner加1。这样CPU1就会发现 inc:next = 1,owner = 1,它就认为自己拿到了锁。 4. 如果在CPU0释放锁之前,CPU2也来竞争这把锁的话,CPU2: slock: owner = 0, next = 3 inc: owner = 0, next = 2。当CPU0释放锁的时候,inc:owner = 1, next = 2,它仍然会 继续循环,等待CPU1释放锁。
references: 1. For SMP cache coherence, please see chapter 4 of Computer Architecture-A Quantitative Approach. 2. Linux kernel source code. 3. For TAS, TTAS concept refer to chapter 7 of The Art of Multiprocessor Programming.
评论