65.9K
CodeProject is changing. Read more.
Home

Spin Lock

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.33/5 (3 votes)

May 22, 2002

2 min read

viewsIcon

170202

downloadIcon

742

Efficient synchronised access to shared resources

Introduction

Spin 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.

Algorithm

Predictably, the algorithm for a spin lock is very simple. Each thread will instantiate a CSpinLock 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 holds the value 0x6b636f6c. This will read "lock" if it is cast to a char *

Implementation

The CSpinLock class implements a spin lock synchronisation object.

Methods

explicit CSpinLock(long *plock = 0)
This is the only class constructor. It passes a pointer to a shared variable to hold the lock value. This parameter can be omitted, in which case an internal class lock variable will be used.

~CSpinLock()
Class destructor. Simply asserts that the object that is going out of scope does not hold the lock.

void lock(void) const
Call this method to acquire a lock to the shared resource.

void unlock(void) const
Call this method to release the lock to the shared resource.

bool has_lock(void) const
Returns true/false to signify if the object currently holds the lock

Usage

The 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 CSpinLock object and the class implementation will ensure that the resource is synchronised correctly.

Contact

Web Site: http://homepage.virgin.net/cdm.henderson
e-mail: cdm.henderson@virgin.net

Revision History

17 Jun 2002 - Initial Revision