多线程编程范例 --- 生成线程/线程池
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; }
相关文章推荐
- 多线程编程范例 --- 生成线程/线程池
- 【学习笔记】多线程编程-线程池/任务/线程
- java高级多线程编程--关于线程的停止问题
- 多线程编程之终止pthread线程
- C# 多线程、异步线程、线程池相关知识
- 多线程编程之三 线程间通讯
- 多线程编程之四——线程的同步(转)
- Java Socket编程 标准范例(多线程)
- Java 多线程编程设计模式之 Thread Pool(线程池)
- 【线程】线程/多线程问题/线程池
- 编程思想之多线程与多进程(2)——线程优先级与线程安全
- 多线程编程之三——线程间通讯
- Linux下简单的多线程编程--线程池的实现
- 【多线程编程】Linux下线程池C实现
- Java多线程编程核心技术---线程间通信(二)
- 编程思想之多线程与多进程(1)-以操作系统的角度述说线程与进程
- 多线程Java Socket编程示例 线程池
- 多线程编程二:调整线程池的大小
- Java6学习笔记56——多线程编程——线程的创建方法2
- 多线程编程之三――线程间通讯