boost库在工作(20)线程之五
来源:互联网 发布:软件源代码管理流程图 编辑:程序博客网 时间:2024/05/17 02:03
通过上面的学习,基本上就可以使用线程了,但怎么样让线程运行类里的成员函数呢?以便封装得更方便使用了。接着下来,就看这个例子,如下:
// boost_013.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include <boost/thread.hpp>#include <boost/bind.hpp>#include <boost/thread/mutex.hpp>//封装线程组运行的类, 并且演示使用类成员函数作为线程组运行函数//软件开发人员: 蔡军生 2013-04-05//QQ: 9073204class CThreadBase{public:void Start(int nMaxCount){//循环地创建N个线程。for (int i = 0; i < nMaxCount; ++i){m_threadGroup.create_thread(boost::bind(&CThreadBase::Run, this, i));}}void Stop(void){//等所有线程退出。m_threadGroup.join_all();}virtual void Run(int nVal){//int nTemp = nVal * nVal;//下面输出需要加锁,不能多个线程共享输出。static boost::mutex mutexCout;boost::lock_guard<boost::mutex> autoLock(mutexCout);std::cout << "thread Run: [" << nVal << "] " << nTemp << std::endl;}private://定义一个线程组对象。boost::thread_group m_threadGroup;};int _tmain(int argc, _TCHAR* argv[]){CThreadBase threadBase;//设置最大的线程个数。threadBase.Start(5);threadBase.Stop();system("PAUSE");return 0;}
在这个例子里封装了一个类CThreadBase,这个类可以表示一个线程运行, 也可以多个线程运行,并且可以让线程运行类里的成员函数,这样更加方便添加代码和管理代码了。在这个例子里,要注意的就是bind器的使用,如下:
m_threadGroup.create_thread(boost::bind(&CThreadBase::Run, this,i));
首先获取成员函数的指针,然后再传送this指针过去,然后就可以调用类实例化的成员函数了。
- boost库在工作(20)线程之五
- boost库在工作(20)线程之五
- boost库在工作(25)任务之五
- boost库在工作(30)网络客户端之五
- boost库在工作(25)任务之五
- boost库在工作(30)网络客户端之五
- boost库在工作(35)网络服务端之五
- boost库在工作(17)线程之二
- boost库在工作(18)线程之三
- boost库在工作(19)线程之四
- boost库在工作(17)线程之二
- boost库在工作(18)线程之三
- boost库在工作(19)线程之四
- boost库在工作(6)作用域智能指针scoped_ptr之五
- boost库在工作(6)作用域智能指针scoped_ptr之五
- boost库在工作(16)线程之一
- boost库在工作(16)线程之一
- boost库在工作(22)任务之二
- 关键字 -- restrict
- 李敖的读书方法
- php对mysql的增删改查
- hdu 1175 连连看 BFS
- HD ACM 2.1.6 整数对
- boost库在工作(20)线程之五
- 动态规划题 UVA Prince and Princess
- itk copy a image
- [CSS]为什么不推荐在CSS中使用ID选择器
- POJ2184-Cow Exhibition
- Eclipse快捷键
- ThreadLocal简单学习
- hdoj_1004 Let the Balloon Rise
- UvaLive-2191-Potentiometers