ATL collection templates: Lock access by critical sections (announce)

ATL collections CAtlArray, CAtlList, CAtlMap are very useful but lack for thread safety features. They are thread unsafe by design and the caller is supposed to take care of access protection is case of multithreaded usage.

However the thread safety protection for the collections is rather typical and a good template can embed all the protection functionality.

Compare the following code passage with whether you would expose all CAtlArray methods of m_ValueArray (if m_ValueArray was declared as CAtlArray) member explicitly implementing access protection within each one.

class CMyArray
{
protected:
mutable CComAutoCriticalSection m_DataLock;
INT m_nValue;
CAtlLockableArrayT{INT, CElementTraits{INT}, CContainedLockTraits} m_ValueArray;

public:
// CMyArray
CMyArray() throw() :
m_ValueArray(m_DataLock)
{
}
INT GetValue() const throw()
{
CComCritSecLock{CComAutoCriticalSection} Lock(m_DataLock);
return m_nValue;
}
CAtlLockableArrayT{INT, CElementTraits{INT}, CContainedLockTraits}& GetValueArray() throw()
{
// NOTE: Like m_nValue/GetValue above, access to m_ValueArray will be protected by
//       m_DataLock critical section. The protection is embedded into m_ValueArray
//       methods so we can expose m_ValueArray directly
return m_ValueArray;
}
};
* template brackets replaced with curvey ones because of WordPress formatting

The critical section aware collections templates save time implementing thread safe classes and shorten code improving its readability.

Categories: ATL

Leave a Reply