MSDK Synchronization Primitives - Blocking Counter
The MSDK Blocking Counter is a simple synchronization primitive that turns out very powerful in modeling threading patterns. It wasn’t originally planned – it emerged during the design of the thread message queue, and proved to be very helpful later on.
Basic API
Blocking Counter is a counter with the following basic methods:
- Increment (operator ++) – never blocks; increments the value of the counter.
- BlockingDecrement (operator --) – if the value of the counter is strictly positive, it decrements it without blocking; if the value of the counter 0, it blocks until another thread increments the value.
Business Meaning
The Blocking Counter has a very common business meaning – it represents a pool of resources. A resource may be added at any time (Increment/++). A resource may be allocated only when there are 1 or more resources in the pool (BlockingDecrement/--). That is the opposite of Semaphore where we start with a fixed number of resources in the pool, and threads “borrow” resources temporarily. Interestingly enough a Semaphore may be modeled using a Blocking Counter, while the other way around is not possible.
Additional API
Additionally the Blocking Counter primitive exposes two blocking methods:
- WaitUntilClear - blocks until the counter value becomes 0 without affecting it.
- WaitUntilDirty - blocks until the counter value becomes positive without affecting it.
Application
A Blocking Counter could be used in queues, stacks, or other data structures, where a pop attempt should block until there is at least one available item. In MSDK Blocking Counters are used in SemiMutex and BlockingSequence, which are further used in ReadWrite and Thread respectively.
Source code:
http://cvs.sourceforge.net/viewcvs.py/msdk/include/bcounter.h?rev=1.4&view=auto
Download MSDK:
http://prdownloads.sourceforge.net/msdk/msdk-2.10.053.tar.gz?download (37K)
SemiMutex is another interesting primitive and it will be the topic of my next post.