在多线程中,往往需要协同处理数据,这里提供一个简单的模版.
template<class TYPE>
class XSelfFreeData
{
class _X_Data
{
public:
CSemaphore m_ref_mutex;
CSemaphore m_data_mutex;
int m_refCount ;
BOOL m_data_locked;
TYPE * m_pValue ;
public:
~_X_Data(){
ASSERT( m_refCount == 0 ) ;
if( m_pValue ){
delete m_pValue ;
}
m_refCount = 0 ;
m_pValue = NULL ;
}
_X_Data(){
m_pValue = new TYPE ;
m_refCount = 1 ;
m_data_locked = FALSE ;
}
void AddRef() {
m_ref_mutex.Lock();
m_refCount ++ ;
m_ref_mutex.Unlock();
}
void Release() {
m_ref_mutex.Lock();
m_refCount -- ;
m_ref_mutex.Unlock();
if( m_refCount == 0 ){
ASSERT( m_data_locked == FALSE ) ;
delete this ;
}
}
void LockData(){
ASSERT( m_refCount > 0 );
m_data_mutex.Lock();
m_data_locked = TRUE ;
}
void UnlockData(){
ASSERT( m_data_locked == TRUE ) ;
m_data_mutex.Unlock();
m_data_locked = FALSE;
}
} ;
_X_Data * m_pData ;
public:
XSelfFreeData( const XSelfFreeData & src )
{
ASSERT( src.m_pData ) ;
m_pData = src.m_pData ;
m_pData->AddRef() ;
}
XSelfFreeData() {
m_pData = NULL ;
}
void Release(){
if( m_pData )
{
m_pData->Release();
m_pData = NULL ;
}
}
BOOL IsNull(){ return m_pData == NULL ; }
void Create(){
if( m_pData ){
m_pData->Release();
}
m_pData = new _X_Data ;
}
~XSelfFreeData(){
if( m_pData ){
m_pData->Release();
}
}
void operator = ( const XSelfFreeData & src ){
if( m_pData ){
m_pData->Release();
}
ASSERT( src.m_pData ) ;
m_pData = src.m_pData ;
m_pData->AddRef() ;
}
void LockData(){ ASSERT( m_pData ) ; m_pData->LockData(); }
/* TYPE * operator ->()
{
ASSERT( m_pData ) ;
return m_pData->m_pValue;
}
*/
void SetValue( const TYPE & value ){
ASSERT( m_pData ) ;
*m_pData->m_pValue = value ;
}
TYPE GetValue(){
ASSERT( m_pData ) ;
return *m_pData->m_pValue ;
}
TYPE * GetValuePtr(){
ASSERT( m_pData ) ;
return m_pData->m_pValue ;
}
void UnlockData(){
ASSERT( m_pData ) ;
m_pData->UnlockData();
}
};
posted on 2006-12-08 22:00
hxb20917 阅读(1112)
评论(0) 编辑 收藏 引用