在xv6 中鎖對象是 spinlock,spinlock中的locked爲1的時候表示被佔用,爲0的時候鎖空閒。函數
struct spinlock { uint locked; // Is the lock held? ...... };
使用 acquire獲取鎖ui
void acquire(struct spinlock *lk) { ........ while(xchg(&lk->locked, 1) != 0); ...... }
該函數中經過xchg原子性交換locked和1,並返回locked的原來的值。當返回值爲1時,說明其餘線程佔用了該鎖,繼續循環等待;當返回值爲0時,說明其餘地方沒有佔用該鎖,同時locked本設置成1了,因此該鎖被此處佔用。atom
static inline uint xchg(volatile uint *addr, uint newval) { uint result; // The + in "+m" denotes a read-modify-write operand. asm volatile("lock; xchgl %0, %1" : "+m" (*addr), "=a" (result) : "1" (newval) : "cc"); /* //最終彙編相似於 movq *addr, %rdx movl newval, %eax lock; xchgl (%rdx), %eax movl %eax, result */ return result; }
xchg經過lock xchg實現原子性的交換,把*addr的老值放入eax中,而後在賦值給result。spa
釋放鎖線程
void release(struct spinlock *lk) { ... // Release the lock, equivalent to lk->locked = 0. // This code can't use a C assignment, since it might // not be atomic. A real OS would use C atomics here. asm volatile("movl $0, %0" : "+m" (lk->locked) : ); ... }