微软相关函数说明:https://docs.microsoft.com/zh-cn/windows/win32/sync/synchronization-functions?redirectedfrom=MSDN
使用原子操作,不需要使用锁等重量级操作,可以设置一个变量,实现自旋锁,
enum
{
LOCK_IS_FREE = 0,
LOCK_IS_TAKEN = 1
};
typedef unsigned LOCK, *PLOCK;
void Lock(PLOCK pl)
{
// If *pl == LOCK_IS_FREE, it is set to LOCK_IS_TAKEN
// atomically, so only 1 caller gets the lock.
// If *pl == LOCK_IS_TAKEN,
// the result is LOCK_IS_TAKEN, and the while loop keeps spinning.
while (_InterlockedCompareExchange((long *)pl,
LOCK_IS_TAKEN, // exchange
LOCK_IS_FREE) // comparand
== LOCK_IS_TAKEN)
{
// spin!
}
}
void Unlock(PLOCK pl) {
_InterlockedExchange((long *)pl, LOCK_IS_FREE);
}
原子函数的汇编代码为:
00B15028 mov ecx,1
00B1502D mov edx,dword ptr [pl]
00B15030 xor eax,eax
00B15032 lock cmpxchg dword ptr [edx],ecx
00B15036 cmp eax,1
使用方法:
LOCK mLock = LOCK_IS_FREE;
Lock(&mLock);
// do something
Unlock(&mLock);