gpt4 book ai didi

assembly - 自旋锁所需的最小 X86 组件是多少

转载 作者:行者123 更新时间:2023-12-02 04:31:37 28 4
gpt4 key购买 nike

在汇编中实现自旋锁。在这里我发布一个我想出的解决方案。这是对的吗?你知道更短的吗?

锁定:

    mov ecx, 0
.loop:
xchg [eax], ecx
cmp ecx, 0
je .loop

发布:

    lock dec dword [eax]

eax 初始化为-1(这意味着锁已释放)。这应该适用于许多线程(不一定是 2 个)。

最佳答案

最短的可能是:

acquire:
lock bts [eax],0
jc acquire

release:
mov [eax],0

为了提高性能,最好使用“测试、测试和设置”方法,并使用暂停,如下所示:

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

关于assembly - 自旋锁所需的最小 X86 组件是多少,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22943572/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com