ATL对象多线程访问临界锁的实现

1. 几个临界区类

ATL将Windows临界区封装了一下,即CComCriticalSection和CComAutoCriticalSection类。两者的实现如下(精简):

class CComCriticalSection
{
public:
    
CComCriticalSection()
    
{  memset(&m_sec, 0, sizeof(CRITICAL_SECTION));   }
    
HRESULT Lock()
    
{  EnterCriticalSection(&m_sec); return S_OK; }
    
HRESULT Unlock()
    
{ LeaveCriticalSection(&m_sec); return S_OK; }
    
HRESULT Init()
    
{
        
InitializeCriticalSection(&m_sec);
        
return S_OK;
    
}
    
HRESULT Term()
    
{ DeleteCriticalSection(&m_sec); return S_OK; }
 
    
CRITICAL_SECTION m_sec;
};
 
class CComAutoCriticalSection : public CComCriticalSection
{
public:
    
CComAutoCriticalSection()
    
{ HRESULT hr = CComCriticalSection::Init(); }
    ~
CComAutoCriticalSection()
    
{ CComCriticalSection::Term(); }
private:
    
HRESULT Init();
    
HRESULT Term();
};

Read the rest of this entry »