|
C++ Programming |
Source
Code
IntroductionSpin locks are a very simple and, in the right context, efficient method of synchronising access to shared resources. The overhead of using Critical Sections or Events for resource acquision is relatively large, but in contrast, a spin lock is very quick. AlgorithmPredictably, the algorithm for a spin lock is very simple. Each thread will instantiate a spin_lock with a shared lock variable. When a shared resource is required, the threads call lock() and when the resource has been finished with, call unlock(). lock() will cause the thread to loop until the resource is available. The availability of the resource is defined by the value of shared variable. If the value of this variable is zero, then the resource is available, otherwise it is in use by another thread. When the resource is locked, the shared variable hold the value 0x6b636f6c. This will read "lock" if it is cast to a char *. ImplementationThe spin_lock class implements a spin lock synchronisation object. Methodsexplicit spin_lock(long *plock = 0) void lock(void) void unlock(void) bool is_locked(void) const UsageThe only decision to be made in using this class is in how the lock variable is used. The easiest use is to omit the ctor parameter and let the class handle this itself. Each resource that is to be shared can be synchronised using a different template parameter value. Each thread can independently instantiate a spin_lock object and the class implementation will ensure that the resource is synchronised correctly. If you want to use the spin lock class to set and reset your own variable, then you can pass a pointer to it to the constructor. This variable must be initialised to zero, otherwise the lock will not work correctly. Warning
|
|||
|
||||