Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2026398
  • 博文数量: 414
  • 博客积分: 10312
  • 博客等级: 上将
  • 技术积分: 4921
  • 用 户 组: 普通用户
  • 注册时间: 2007-10-31 01:49
文章分类

全部博文(414)

文章存档

2011年(1)

2010年(29)

2009年(82)

2008年(301)

2007年(1)

分类: C/C++

2010-07-09 23:21:42

 线程池的初始化,与取得线程的标准调用范例:
 

/*
 ******************************************************************************
 *
 * BThread :: ThreadFunction
 *
 ******************************************************************************
 */

    
void * BaseThread :: ThreadFunction( void * pData )
{
         // 保存该线程引涉指针存储到特定的线程数据对象中

    if ( s_ThreadKey != 0x10000l)
        pthread_setspecific( s_ThreadKey, pData );
       
        // pData的值是一个指针,该指针引涉到该线程示例对象本身

         BThread * pself = (BThread *)pData;
                  pself->ThreadMethod();
      
    // 如果线程数据对象无效,那么从线程数据对象中删除上面的引涉指针,使用NULL来代替pData的方法达到目的

    if ( s_ThreadKey != INVALID_PTHREAD_KEY )
        pthread_setspecific( s_ThreadKey, NULL );
      
         // 线程退出标志符,首先设定为false

                pself->m_bRunningFlag = false;
         return NULL;
}
  
  
/*
 ******************************************************************************
 *
 * BThread :: Run
 *
 ******************************************************************************
 */

int BThread :: Run( void )
{
   pthread_attr_t thread_attr;
   int Result;
       
    // 我们队每个线程的启动都调用Run()方法

    assert( !m_bRunningFlag );
    if ( m_bRunningFlag )
       return 0;
  
    // 初始化线程的属性,使用pthread_attr_init方法

    Result = pthread_attr_init( &thread_attr );
    if ( Result != 0 ) {
        m_LastError = errno;
        return 202;
    }
  
    // 设定线程分离态(detached): 使用pthread_attr_setdetachstate方法

    if ( m_bDetached ) {
       Result = pthread_attr_setdetachstate( &thread_attr, PTHREAD_CREATE_DETACHED );
        if ( Result != 0 ) {
            m_LastError = errno;
            return 202;
        }
    }
  
    // 设定线程池(栈)的大小: 使用pthread_attr_setstacksize方法

    size_t m_StackSize = m_StackSize>0 ? m_StackSize:1024*1024;
    if ( m_StackSize > 0 ) {
        Result = pthread_attr_setstacksize( &thread_attr, m_StackSize );
        if ( Result != 0 ) {
            m_LastError = errno;
            return 202;
        }
    }
  
    // 生成欲求的线程,使用pthread_create方法

    Result = pthread_create( &m_ThreadID, &thread_attr, &ThreadFunction, this );
    if ( Result != 0 ) {
        m_LastError = errno;
        return 202;
    }
    //清楚中间数据-pthread_attr_t : 使用pthread_attr_destroy方法

    pthread_attr_destroy( &thread_attr );
  
    m_bJoinable = true;
    m_bRunningFlag = true;
    return 0;
}


阅读(1241) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~