1.CComSingleThreadModel和CComMultiThreadModel特征类:
class CComSingleThreadModel
{
public:
static ULONG WINAPI Increment(LPLONG p) throw() {return ++(*p);}
static ULONG WINAPI Decrement(LPLONG p) throw() {return --(*p);}
typedef CComFakeCriticalSection AutoCriticalSection;
typedef CComFakeCriticalSection CriticalSection;
typedef CComSingleThreadModel ThreadModelNoCS;
};
class CComMultiThreadModel
{
public:
static ULONG WINAPI Increment(LPLONG p) throw() {return InterlockedIncrement(p);}
static ULONG WINAPI Decrement(LPLONG p) throw() {return InterlockedDecrement(p);}
typedef CComAutoCriticalSection AutoCriticalSection;
typedef CComCriticalSection CriticalSection;
typedef CComMultiThreadModelNoCS ThreadModelNoCS;
};
其中的CFakeCriticalSection定义如下:
class CComFakeCriticalSection
{
public:
HRESULT Lock() throw() { return S_OK; }
HRESULT Unlock() throw() { return S_OK; }
HRESULT Init() throw() { return S_OK; }
HRESULT Term() throw() { return S_OK; }
};
这两个类提供了针对特定套间对象的同步控制支持。
CComSingleThreadModel适用于单线程套间对象,它不采用任何线程同步机制;CComMultiThreadModel适用于多线程套间对象,它使用win32的同步机制来实现。
2.CComObjectRootEx模板类
template <class ThreadModel>
class CComObjectRootEx : public CComObjectRootBase
{
public:
typedef ThreadModel _ThreadModel;
typedef typename _ThreadModel::AutoCriticalSection _CritSec;
typedef CComObjectLockT<_ThreadModel> ObjectLock;
ULONG InternalAddRef()
{
return _ThreadModel::Increment(&m_dwRef);
}
ULONG InternalRelease()
{
return _ThreadModel::Decrement(&m_dwRef);
}
void Lock() {m_critsec.Lock();}
void Unlock() {m_critsec.Unlock();}
private:
_CritSec m_critsec;
};
它使用传入的线程模型特征类来实现对象独立存在时所需要的引用计数支持,同时提供了一个方便对象开发使用的同步锁,我们可以使用这个锁来完成对自定义数据访问的保护。
posted on 2007-04-06 14:39
michael 阅读(1607)
评论(0) 编辑 收藏 引用 所属分类:
心得