我的建议是使用CMPXCHG
指令。该指令基本上结合了单一操作中的比较和交换。它将源操作数与目标操作数进行比较,并相应地设置标志。然后,如果它们相等(ZF == 1),则它将来自源的值复制到目标中。否则(ZF == 0),它将单独离开目的地。结合LOCK
前缀,这对于多线程环境中的原子操作很方便,因为它允许您安全地更新存储在共享内存中的值。
CMPXCHG
唯一需要注意的是它需要Pentium或更高版本的处理器。今天,这显然不是一个问题,但如果你正在做复古编程,你可能需要看别的地方。 (当然,复古程序员不必担心多个处理器,并且通常甚至没有多个线程。)
这是一个二进制信号量的示例实现,用伪MASM-风格的语法。二进制信号量是其值为0(解锁)或1(锁定)的信号量。
; This function attempts to obtain the semaphore.
;
; It compares the current value of the semaphore to 0. If it is 0, that means
; the semaphore is not currently locked (i.e., it is available), so this function
; sets it to 1, thus marking it as locked. Otherwise, if the semaphore is already locked,
; this function blocks (waits indefinitely) until it becomes available,
; and then locks it as described above.
;
; The address of the semaphore flag to lock is passed on the stack.
; It is the caller's responsibility to clean the stack (__cdecl).
;
; Clobbers: EAX, EDX
Lock PROC
mov edx, DWORD PTR [esp + 4] ; get address of semaphore (passed as sole parameter on stack)
WaitUntilAvailable:
mov eax, 1
lock cmpxchg DWORD PTR [edx], eax
jz Finished
; TODO: Add code to suspend the thread (yield execution) while waiting,
; for example by calling the Win32 Sleep function.
; Currently, this just spins a busy loop.
jmp WaitUntilAvailable
Finished:
ret
Lock ENDP
; This function releases the semaphore.
;
; If the semaphore is currently locked (has a value of 1), it is reset to 0.
;
; The address of the semaphore flag to lock is passed on the stack.
; It is the caller's responsibility to clean the stack (__cdecl).
;
; Clobbers: EAX, EDX
Unlock PROC
mov edx, DWORD PTR [esp + 4]
xor eax, eax
lock cmpxchg DWORD PTR [edx], eax
ret
Unlock ENDP
如果你愿意,你可以很容易地修改这些来为计数信号量工作。在这种情况下,由于您想实际增加/减少该值,因此可以使用XADD
指令。我知道这是在486和更高版本上支持的事实,再加上它比CMPXCHG
快得多。下面是代码可能的样子:
; Waits for a semaphore to become available.
;
; If the value of the semaphore variable is non-zero, decrement it by 1 and return.
; Otherwise, block execution until the semaphore's value is greater than
; or equal to 1 (i.e., add the caller to the semaphore's queue and wait
; until it becomes available).
;
; Clobbers: EAX, EDX
SemaphoreWait PROC
mov edx, DWORD PTR [esp + 4]
jmp Check
WaitUntilAvailable:
pause ; (or some other way to yield)
Check:
mov eax, DWORD PTR [edx]
test eax, eax
jle Check
mov eax, -1
lock xadd DWORD PTR [edx], eax
test eax, eax
jg Finished
lock inc DWORD PTR [edx]
jmp WaitUntilAvailable
Finished:
ret
SemaphoreWait ENDP
; Signals (releases) a semaphore, incrementing its value by 1.
;
; Clobbers: EAX
SemaphoreSignal PROC
mov eax, DWORD PTR [esp + 4]
lock inc DWORD PTR [eax]
ret
SemaphoreSignal ENDP
当然,使用互斥锁来保护信号量。 –