boost线程之类成员函数

来源:互联网 发布:mac 口红brave 编辑:程序博客网 时间:2024/05/28 20:18

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

#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(){};voidFunc();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;}


0 0
原创粉丝点击