ACE主动对象模式学习

利用ACE实现主动对象模式,主动对象派生于 ACE_Task,在任务线程内执行异步方法,每个异步方法需封装成派生自 ACE_Method_Object的类,而ACE_Activation_Queue作为异步方法类对象的队列,ACE_Future对象用来指定异步对象操作的结果.下面继续练练自己的笨手了:
// 异步处理的方法封装.需从ACE_Method_Object派生,并实现call方法
class   CAsyncCount :  public   ACE_Method_Object
{
private :
    
int   m_nMax;
    ACE_Future
< int >   m_futureRet;
public
    CAsyncCount( 
int  nMax, ACE_Future < int >  futureRet ) 
    {
        m_nMax         
=   nMax;
        m_futureRet   
=   futureRet;
    }

    
virtual   int  call ( ) 
    {
        ACE_Time_Value tmWait( 
0 10000  );
        
int   nSum  =   0 ;
        
for  (  int  nIndex  =   1 ; nIndex  <=  m_nMax; nSum  +=  nIndex,nIndex ++  )
        {
            
// 每次执行等待10ms
            ACE_OS::sleep( tmWait );
        }
        
// 将结果设置到ACE_Future对象
         this -> m_futureRet. set ( nSum );

        
return   - 1 ;
    }
};


// 主动对象
class   CTaskDemo :  public  ACE_Task < ACE_MT_SYNCH >
{
private :
    
// 保存异步任务队列
    ACE_Activation_Queue  m_activeQueue;

public :
    
virtual   int  open ( void   * args  =   0 )
    {
        
// 创建一个线程
         this -> activate( THR_NEW_LWP,  1  );
        
return   0 ;
    }
    
virtual   int  close (u_long flags  =   0 )
    {
        
if  ( ACE_OS::thr_equal ( ACE_Thread::self (),     this -> last_thread () ) )
        {
            
// 释放对象
            delete  this ;
        }

        
return   0 ;
    }
    
virtual   int  svc ( void )
    {
        
while  (  true  )
        {
            
// 用智能指针方便自动释放指针对象
            CAutoPtr < ACE_Method_Object >   spMethodObj( m_activeQueue.dequeue() );

            
// 约定的退出机制,若call返回-1则推出
             if - 1   ==  spMethodObj -> call() )
                
break ;
        }

        
return   0 ;
    }

public :
    ACE_Future
< int >   AsyncCount(  int  nMax )
    {
        ACE_Future
< int >   futureRet;
        
// 添加异步任务到队列
         this -> m_activeQueue.enqueue(  new  CAsyncCount( nMax, futureRet ) );
        
return  futureRet;
    }
};
调用示例:
        CTaskDemo   * pTask  =   new  CTaskDemo;
        pTask
-> open( );

        
// 调用异步方法
        ACE_Future < int >   futureRet  =  pTask -> AsyncCount(  100  );

        
do  
        {
            AtlTrace( _T(
" No Complete Yet\n " ) );
        } 
while ! futureRet.ready() );   // 等待异步方法执行完
        
        
int  nSum(  0  );
        futureRet.
get ( nSum );   // 获取执行结果
        AtlTrace( _T( " The Result is %d\n " ), nSum );

        ACE_Thread_Manager::instance()
-> wait();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值