MSDK Synchronization Primitives - SemiMutex
SemiMutex is a sophisticated type of mutex that mixes exclusive- and shared locks following this widely accepted concept:
- An attempt to perform an exclusive lock blocks until all active locks are released.
- An attempt to perform a shared lock blocks until an eventual active exclusive lock is released.
The tricky part is how to make an attempt for an exclusive lock block subsequent lock attempts of either kind while waiting for all shared locks to be released with using minimum system resources.
MSDK provides a very elegant implementation where each method consists of literally a couple of programming lines. That is made possible by the Blocking Counter that is used internally. Each shared/read lock increments the Blocking Counter while its corresponding release decrements it. At entry-level access is serialized through a regular mutex which holds subsequent lock attempts. Now for an exclusive lock attempt to patiently wait for all shared locks to be released without consuming CPU cycles, all it needs is to call WaitUntilClear() on the embedded Blocking Counter. That is hooked on the internal Clear Event member of the Blocking Counter that is signaled in a permanent manner when the counter value becomes 0.
SemiMutex makes the implementation of the Single-Writer–Multiple-Readers multithreading pattern absolutely trivial.
Enjoy!
Source code:
http://cvs.sourceforge.net/viewcvs.py/msdk/include/semimutex.h?rev=1.2&view=auto
Download MSDK:
http://prdownloads.sourceforge.net/msdk/msdk-2.10.053.tar.gz?download (37K)