mel*_*des 2 x86 assembly spinlock
在程序集中实现自旋锁.在这里,我发布了一个我提出的解决方案.这是对的吗?你知道一个较短的吗?
锁:
mov ecx, 0
.loop:
xchg [eax], ecx
cmp ecx, 0
je .loop
Run Code Online (Sandbox Code Playgroud)
发布:
lock dec dword [eax]
Run Code Online (Sandbox Code Playgroud)
eax初始化为-1(这意味着锁是免费的).这适用于许多线程(不一定是2).
最短的可能是:
acquire:
lock bts [eax],0
jc acquire
release:
mov [eax],0
Run Code Online (Sandbox Code Playgroud)
为了性能,最好使用"测试,测试和设置"方法,并使用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
Run Code Online (Sandbox Code Playgroud)
对于调试,您可以添加额外的数据,以便更容易地检测问题,如下所示:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
743 次 |
| 最近记录: |