多线程编程范例 --- 生成线程/线程池
线程池的初始化,与取得线程的标准调用方法
/* ****************************************************************************** * * 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; }
posted on 2010-07-27 13:49 sohu2000000 阅读(352) 评论(0) 收藏 举报
浙公网安备 33010602011771号