I’m working on win 32 multithreading with c++. Scenario: I have a function used by multiple threads. This function as a critical sections (or any kind of construct that can lock a resource). In the critical section an exception is thrown. At this point I need to take care of unlocking the resource in the exception catch block.
Is there any other way that this can be done? I mean, let’s say that I don’t want to have to remember to release the lock in the catch block, is there any common way to handle this problem to avoid this error prone scenario?
The idea is to encapsulate the act of acquiring and releasing the critical section in an object such that constructing the object acquires the CS and destroying the object releases it.
The concept is called RAII – Resource Acquisition is Initialization. It is a very common idiom in modern C++.