C++ coding style: Convenience vs. Understandability

You know a coding pattern for writing a smart pointer. Because it is easy to forget to free some memory space which is created in a function, Creating a dynamic memory space with help of static typing is the basic idea.

For synchronization, the same pattern can be used.

class C_CRITICAL_SECTION : public CRITICAL_SECTION
{
public:
    C_CRITICAL_SECTION()
    {
        InitializeCriticalSection(this);
    }

    ~C_CRITICAL_SECTION()
    {
        DeleteCriticalSection(this);
    }
};

class CSynchronizeAccess
{
public:
    CSynchronizeAccess(CRITICAL_SECTION &lock)
	: m_Lock(lock)
    {
        EnterCriticalSection(&m_Lock);
    }

    ~CSynchronizeAccess()
    {
        LeaveCriticalSection(&m_Lock);
    }

private:
    CRITICAL_SECTION &m_Lock;
};

How to use it is like this.

C_CRITICAL_SECTION gLockInit;

void CImportantClass::Initialize( StreamerInterfaceDefinitions::StreamerInitializeInterface &info )
{
    CSynchronizeAccess lock( gLockInit );
    
    ....
}

How much portion of the Initialize method covered by the gLockInit? Within the scope of “lock”, everything is protected by the synchronization variable.

However, without above convenient coding pattern, it will be usually written like this.

CSingleLock singleLock(&m_CritSection);
singleLock.Lock();
// resource locked
//.usage of shared resource...

singleLock.Unlock();

What is the difference? You should explictly Lock() and Unlock(). What is good about it is that the protected block is very visible. So, you don’t remember how the synchronization class is implemented., or you can control the range of protected part of your code more freely.

So, which style do you prefer? :)

Oh.. one more thing.
C_CRITICAL_SECTION let’s you write cleaner code, because you don’t need to explictly call InitializeCriticalSection and DeleteCriticalSection. Same thing can be said for the CSynchronizeAccess.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: