How to catch the exception thrown in a critical section?

I am working on 32 C ++ multi-threaded call. Scenario: I have a function used by multiple threads. This function is a critical sector (or any construct that may block a resource). An exception is thrown in the critical section. At this point, I need to take care of unlocking the resource in the catch catch block.

Is there any other way that this can be done? I mean, let's say that I do not want to forget to release the lock in the catch block, is there any general way to handle this problem in order to avoid this error scenario?

+4
source share
4 answers

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); // lock is held until lockIt is destroyed } 

This concept is called RAII - Resource Initialization - Initialization. This is a very common idiom in modern C ++.

+16
source

If you are using existing infrastructure, you probably already have a container of RAII classes that can do this for you. If you use MFC, look at CSingleLock ; if you use boost, look at scoped_lock .

This is a shame that everyone seems to have to (or think that he should) roll their own.

+3
source

Write a parenthesis class that takes a critical section as a constructor parameter. Call EnterCriticalSection in the constructor and LeaveCriticalSection in the destructor. Deploying the stack will do the rest if a C ++ exception is thrown.

+2
source

If you can use MFC, you can use CSingleLock for this. You can use it as follows:

 void f() { try { CSingleLock lock(&m_criticalSection, TRUE); } catch(/*some exception*/) } 

The lock will take care of unlocking the critical section in its destructor. Since lock is a local object, when an exception is thrown by dropping the stack and the destructor of the lock objects is executed, unlocking your critical section.

+2
source

All Articles