Let’s assume the existence of the following function in C++:
int InterlockedExchange(LPINT target, INT value);
or in C#:
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:
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
// some code that accesses sharedValue
Implement the class SpinLock either in C++ or in C#.