The idea is to encapsulate the act of receiving and releasing a critical section in an object, so that building the object acquires CS and destroys the object, freeing it.
struct CSHolder { explicit CSHolder(CRITICAL_SECTION& cs): lock(cs) { ::EnterCriticalSection(&lock); } ~CSHolder() { ::LeaveCriticalSection(&lock); } CRITICAL_SECTION& lock; }; CRITICAL_SECTION gLock; void foo() { CSHolder lockIt(gLock);
This concept is called RAII - Resource Initialization - Initialization. This is a very common idiom in modern C ++.
source share