自旋鎖計算機科學用於多線程同步的一種,線程反覆檢查鎖變量是否可用。由於線程在這一過程中保持執行,因此是一種忙等待。一旦獲取了自旋鎖,線程會一直保持該鎖,直至顯式釋放自旋鎖。

自旋鎖避免了進程上下文的調度開銷,因此對於線程只會阻塞很短時間的場合是有效的。因此作業系統的實現在很多地方往往用自旋鎖。Windows作業系統提供的輕型讀寫鎖(SRW Lock)內部就用了自旋鎖。顯然,單核CPU不適於使用自旋鎖,這裏的單核CPU指的是單核單線程的CPU,因為,在同一時間只有一個線程是處在運行狀態,假設運行線程A發現無法獲取鎖,只能等待解鎖,但因為A自身不掛起,所以那個持有鎖的線程B沒有辦法進入運行狀態,只能等到作業系統分給A的時間片用完,才能有機會被調度。這種情況下使用自旋鎖的代價很高。

獲取、釋放自旋鎖,實際上是讀寫自旋鎖的存儲內存或寄存器。因此這種讀寫操作必須是原子的。通常用test-and-set等原子操作來實現。[1]

Windows內核API

  • KeInitializeSpinLock //初始化自旋鎖
  • KeAcquireSpinLock //獲取自旋鎖
  • KeReleaseSpinLock //釋放自旋鎖

例子

匯編語言寫的代碼,運行於Intel 80386兼容處理器。

; Intel syntax

locked:                      ; The lock variable. 1 = locked, 0 = unlocked.
     dd      0

spin_lock:
     mov     eax, 1          ; Set the EAX register to 1.

     xchg    eax, [locked]   ; Atomically swap the EAX register with
                             ;  the lock variable.
                             ; This will always store 1 to the lock, leaving
                             ;  the previous value in the EAX register.

     test    eax, eax        ; Test EAX with itself. Among other things, this will
                             ;  set the processor's Zero Flag if EAX is 0.
                             ; If EAX is 0, then the lock was unlocked and
                             ;  we just locked it.
                             ; Otherwise, EAX is 1 and we didn't acquire the lock.

     jnz     spin_lock       ; Jump back to the MOV instruction if the Zero Flag is
                             ;  not set; the lock was previously locked, and so
                             ; we need to spin until it becomes unlocked.

     ret                     ; The lock has been acquired, return to the calling
                             ;  function.

spin_unlock:
     mov     eax, 0          ; Set the EAX register to 0.

     xchg    eax, [locked]   ; Atomically swap the EAX register with
                             ;  the lock variable.

     ret                     ; The lock has been released.

參見

參考文獻

  1. ^ Silberschatz, Abraham; Galvin, Peter B. Operating System Concepts Fourth. Addison-Wesley. 1994: 176–179. ISBN 0-201-59292-4. 

外部連結