自旋鎖
外觀
自旋鎖是計算機科學用於多執行緒同步的一種鎖,執行緒反覆檢查鎖變量是否可用。由於執行緒在這一過程中保持執行,因此是一種忙等待。一旦獲取了自旋鎖,執行緒會一直保持該鎖,直至顯式釋放自旋鎖。
自旋鎖避免了進程上下文的調度開銷,因此對於執行緒只會阻塞很短時間的場合是有效的。因此作業系統的實現在很多地方往往用自旋鎖。Windows作業系統提供的輕型讀寫鎖(SRW Lock)內部就用了自旋鎖。顯然,單核CPU不適於使用自旋鎖,這裡的單核CPU指的是單核單執行緒的CPU,因為,在同一時間只有一個執行緒是處在運行狀態,假設運行執行緒A發現無法獲取鎖,只能等待解鎖,但因為A自身不掛起,所以那個持有鎖的執行緒B沒有辦法進入運行狀態,只能等到作業系統分給A的時間片用完,才能有機會被調度。這種情況下使用自旋鎖的代價很高。
獲取、釋放自旋鎖,實際上是讀寫自旋鎖的存儲內存或暫存器。因此這種讀寫操作必須是原子的。通常用test-and-set等原子操作來實現。[1]
Windows內核API
[編輯]- KeInitializeSpinLock //初始化自旋鎖
- KeAcquireSpinLock //獲取自旋鎖
- KeReleaseSpinLock //釋放自旋鎖
例子
[編輯]; 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.
參見
[編輯]參考文獻
[編輯]- ^ Silberschatz, Abraham; Galvin, Peter B. Operating System Concepts Fourth. Addison-Wesley. 1994: 176–179. ISBN 0-201-59292-4.
外部連結
[編輯]- pthread_spin_lock documentation (頁面存檔備份,存於網際網路檔案館) from The Open Group Base Specifications Issue 6, IEEE Std 1003.1, 2004 Edition
- Variety of spinlock Implementations (頁面存檔備份,存於網際網路檔案館) from Concurrency Kit
- Article "User-Level Spin Locks - Threads, Processes & IPC" by Gert Boddaert
- Paper "The Performance of Spin Lock Alternatives for Shared-Memory Multiprocessors (頁面存檔備份,存於網際網路檔案館)" by Thomas E. Anderson
- Paper "Algorithms for Scalable Synchronization on Shared-Memory Multiprocessors" by John M. Mellor-Crummey and Michael L. Scott. This paper received the 2006 Dijkstra Prize in Distributed Computing (頁面存檔備份,存於網際網路檔案館).
- Spin-Wait Lock (頁面存檔備份,存於網際網路檔案館) by Jeffrey Richter
- Austria C++ SpinLock Class Reference (頁面存檔備份,存於網際網路檔案館)
- Interlocked Variable Access(Windows) (頁面存檔備份,存於網際網路檔案館)
- Operating Systems: Three Easy Pieces (Chapter: Locks) (頁面存檔備份,存於網際網路檔案館)