boost库在工作(20)线程之五

通过上面的学习,基本上就可以使用线程了,但怎么样让线程运行类里的成员函数呢?以便封装得更方便使用了。接着下来,就看这个例子,如下:

// 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: 9073204
class 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指针过去,然后就可以调用类实例化的成员函数了。


原文地址:https://www.cnblogs.com/javawebsoa/p/3034447.html