最短的可能是:
acquire:
lock bts [eax],0
jc acquire
release:
mov [eax],0
对于性能,最好使用“测试、测试和设置”方法,并使用pause
, 像这样:
acquire:
lock bts [eax],0 ;Optimistic first attempt
jnc l2 ;Success if acquired
l1:
pause
test [eax],1
jne l1 ;Don't attempt again unless there's a chance
lock bts [eax],0 ;Attempt to acquire
jc l1 ;Wait again if failed
l2:
release:
mov [eax],0
为了进行调试,您可以添加额外的数据以更轻松地检测问题,如下所示:
acquire:
lock bts [eax],31 ;Optimistic first attempt
jnc l2 ;Success if acquired
mov ebx,[CPUnumber]
lea ebx,[ebx+0x80000000]
cmp [eax],ebx ;Is the lock acquired by this CPU?
je .bad ; yes, deadlock
lock inc dword [eax+4] ;Increase "lock contention counter"
l1:
pause
test [eax],0x80000000
jne l1 ;Don't attempt again unless there's a chance
lock bts [eax],31 ;Attempt to acquire
jc l1 ;Wait again if failed
l2: mov [eax],ebx ;Store CPU number
release:
mov ebx,[CPUnumber]
lea ebx,[ebx+0x80000000]
cmp [eax],ebx ;Is lock acquired, and is CPU same?
jne .bad ; no, either not acquired or wrong CPU
mov [eax],0