boost线程之类成员函数

首先,是准备工作,包含头文件

#include <iostream>
#include <boost/bind.hpp>
#include <boost/thread.hpp>
#include <boost/thread/mutex.hpp>

using namespace std;

//线程休眠,毫秒级
#define  BOOST_SLEEP(n)  boost::thread::sleep(boost::get_system_time()+boost::posix_time::millisec(n))

然后,创建一个简单的类CTest,

class CTest
{
public:
	CTest(){};
	~CTest(){};

	void		Func();
	static void FuncThread(void *pData);
};

void CTest::Func()
{
	cout<<"here is CTest::Func this="<<this<<endl;
	boost::thread thTest(boost::bind(CTest::FuncThread,this));
	thTest.join();
}
void CTest::FuncThread(void *pData)
{
	CTest *pOwner = (CTest*)pData;
	while(1)
	{
		cout<<"here is CTest::FuncThread  running. this="<<pOwner<<endl;
		BOOST_SLEEP(1000);
	}
}

最后,测试一下

int _tmain(int argc, _TCHAR* argv[])
{
    CTest test;
    test.Func();
    return 0;
}

关键点在于,作为线程的成员函数,必须是静态的。


测试第二下,在类外部调用类成员函数产生线程

int _tmain(int argc, _TCHAR* argv[])
{
    CTest test;
    boost::thread thTest(boost::bind(CTest::FuncThread,&test));
    thTest.join();

    return 0;

}


posted on 2017-10-12 21:27  zhuxian2009  阅读(766)  评论(0编辑  收藏  举报

导航