您的位置:首页 > 编程语言

多线程编程范例 --- 生成线程/线程池

2010-07-27 13:49 351 查看
线程池的初始化,与取得线程的标准调用方法

/*
******************************************************************************
*
*   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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: