Multi threaded application requires the synchronization of resources to avoid issues related to resource sharing. One of the problem which occurs while using Windows API’s for synchronization is that in between lock and unlock statements if some exception occurs. Resource may get locked forever.
This can be avoided with simply wrapping up the synchronization object inside dummy local objects so that as soon as program comes to the end of the block or stack unwinding, destruction for such object gets called and resource gets unlocked.
Ex Code where resource can be locked forever.
CRITICAL_SECTION cs;
InitializeCriticalSection(&cs)
EnterCriticalSection(&cs)
//Access resource.
//If anything goes wrong here, ex. exception thrown, resource will be forever locked.
LeaveCriticalSection(&cs);
DeleteCriticalSection(&cs);
Ex Code – Solution
Declare a class as below
class SyncObject
{
CRITICAL_SECTION cs;
public:
SyncObject()
{
InitializeCriticalSection(&cs);
EnterCriticalSection(&cs);
}
~SyncObject()
{
LeaveCriticalSection(&cs);
DeleteCriticalSection(&cs);
}
};
Usage :
{
SyncObject lockResource;
// Access resource
// Even if exception thrown object will destroyed during stack unwinding and resource will be unlocked.
}