Tuesday, October 27, 2009

ATL Removal: Part 5 – Changing ATL’s Lock and Unlock to Slim Reader/Writer (SRW) Locks

You may encounter Lock() and Unlock() calls in your ATL based code to synchronize the usage of shared memory amongst your threads. You get these bonus methods thanks to inheriting from ATL base classes (CComObjectRoot). Since we are removing ATL, we will have to find an alternative. Enter Slim Reader/Writer (SRW) locks.

SRW locks are not loaded with tons of features like some of the other locks that Microsoft has to offer ; however, they fast and easy on the memory foot print. In fact, you can consider using SRW locks instead of ATL locking as a performance enhancement. I won’t get into SRW locks here, but you can read more about them on MSDN here:

http://msdn.microsoft.com/en-us/library/aa904937%28VS.85%29.aspx

The first thing to do is add a SRWLOCK member like so:

SRWLOCK m_Lock;

Then in your class’ constructor add the initialization:

InitializeSRWLock(&m_Lock);

Replace Lock() with this:

AcquireSRWLockExclusive(&m_Lock);

And Unlock() with this:

ReleaseSRWLockExclusive(&m_Lock);

As you can see from the MSDN documentation SRW locks can do more than exclusive locks. You might want to look at these other SRW functions to give your critical sections just the right amount of protection.

The following are the SRW lock functions (from MSDN).

SRW lock functionDescription
AcquireSRWLockExclusiveAcquires an SRW lock in exclusive mode.
AcquireSRWLockSharedAcquires an SRW lock in shared mode.
InitializeSRWLockInitialize an SRW lock.
ReleaseSRWLockExclusiveReleases an SRW lock that was opened in exclusive mode.
ReleaseSRWLockSharedReleases an SRW lock that was opened in shared mode.
SleepConditionVariableSRWSleeps on the specified condition variable and releases the specified lock as an atomic operation.

No comments:

Post a Comment