随笔 - 1  文章 - 0  trackbacks - 0
<2006年12月>
262728293012
3456789
10111213141516
17181920212223
24252627282930
31123456

常用链接

留言簿(1)

随笔档案

搜索

  •  

最新评论

在多线程中,往往需要协同处理数据,这里提供一个简单的模版.

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)  编辑 收藏 引用

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理