32,944
社区成员




Spin lock
Let’s assume the existence of the following function in C++:
int InterlockedExchange(LPINT target, INT value);
or in C#:
class Interlocked
{
public static int Exchange (ref int target, int value);
}
This function atomically exchanges a pair of 32-bit values by writing the new value at the position pointed by
target, and returning the prior value of the int value pointed to by target.
Using this function, we want to implement a SpinLock class that can be used as a thread synchronization
mechanism to synchronize the access when multiple threads concurrently execute code that writes to or
modifies the same resource.
The SpinLock class should have the following interface:
class SpinLock
{
public:
void Enter(); // acquire the spinlock
void Exit(); // release the spinlock
};
For example, assume there is a variable (sharedValue) accessed and modified by a function
(threadSafeFunction()). Since this function may be concurrently executed by several threads, we can use a
SpinLock to make the function thread- safe in the following way:
static int sharedValue; // shared resource
static SpinLock lock; // lock for the resource
void threadSafeFunction() // executed by multiple threads
{
lock.Enter();
//
// some code that accesses sharedValue
//
lock.Exit();
}
Implement the class SpinLock either in C++ or in C#.
- while(lockval);
- Exchange(lockval, 1); //上锁
+while(Exchange(lockval, 1) == 1); //如果一直上锁状态,那么返回值一直是1,==1在C语言中也可以省略,如果某瞬间开锁,那么它枷锁,返回0,循环结束
int lockval = 1;//初始化值
enter()
{
while(lockval); //如果锁一直上锁状态,则死循环等待,如果某瞬间此锁已经开锁,则上锁
Exchange(lockval, 1); //上锁
}
exit()
{
Exchange(lockval, 0);//开锁
}