Domanda

I have a class which declares a CCriticalSection object. Lets say for simplicity that only one thread should enter and execute the methods of that class at a time.

My question here is,

Are there any differences in me declaring a class level CSingleLock and use it's Lock() and Unlock() method and me declaring CSingleLock object in each function.

class ExclusiveClass
{
    CCriticalSection mCS;
    CSingleLock      mSL;
    ExclusiveClass() : mCS(), mSL(&mCS) { }
    void someMethod 
    {
        mSL.Lock();
        // Do whatever you want
        mSL.Unlock();
    }
}

versus

class ExclusiveClass
{
    CCriticalSection mCS;
    ExclusiveClass() : mCS() {}
    void someMethod 
    {
        CSingleLock sl(&mCS);
        sl.Lock()
        // Do whatever you want
        sl.Unlock();
    }
}

I know one definitive difference. In second approach, we need not call the Unlock() method explicitly. Upon returning from a function, the sl's destructor will be called and the method lock will unlock automatically.

My concern here is wrt exceptions. When an exception happens, I am for sure the second approach will unlock automatically. What about first approach ? And are there any other differences.

È stato utile?

Soluzione

Your first example isn't exception safe. If something throws an exception after the Lock but before the call to Unlock you'll never release the lock, which is bad!

For this sort of pattern you should use the RAII approach that you show in your second example. Not only is it exception safe but it saves you having to worry about calling Unlock, which you could easily forget to do and get some difficult to track down errors.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top