Lightweight Lock

This lightweight lock class was adapted from samples and ideas that were put across the ATL mailing list. It is a non-starving, kernel- free lock that does not order writer requests. It is optimized for use with resources that can take multiple simultaneous reads, particularly when writing is only an occasional task.

Multiple readers may acquire the lock without any interference with one another. As soon as a writer requests the lock, additional readers will spin. When the pre-writer readers have all given up control of the lock, the writer will obtain it. After the writer has rescinded control, the additional readers will gain access to the locked resource.

This class is very lightweight. It does not use any kernel objects. It is designed for rapid access to resources without requiring code to undergo process and ring changes. Because the "spin" method for this lock is "Sleep(0)", it is a good idea to keep the lock only long enough for short operations; otherwise, CPU will be wasted spinning for the lock. You can change the spin mechanism by #define'ing COMET_LW_LOCK_SPIN before including this header file.

VERY VERY IMPORTANT: If you have a lock open with read access and attempt to get write access as well, you will deadlock! Always rescind your read access before requesting write access (and, of course, don't rely on any read information across this).

This lock works in a single process only. It cannot be used, as is, for cross-process synchronization. To do that, you should convert this lock to using a semaphore and mutex, or use shared memory to avoid kernel objects.