且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

boost thread 类的非静态函数作为线程函数

更新时间:2021-10-28 10:47:07

1测试例子

#include <iostream>

#include <string>

#include <boost/thread/thread.hpp>


void ThreadFunc()

{

std::cout << "Welcome to thread function" << std::endl;

}

int main(int argc, char* argv[])

{

boost::thread instance(&ThreadFunc);

instance.join();

return 0;

}


2 携带参数例子

#include <boost/thread/thread.hpp>

#include <boost/bind.hpp>

#include <iostream>


void threadFunc(const char* pszContext)

{

std::cout << pszContext << std::endl;

}


int main(int argc, char* argv[])

{

char* pszContext = "fengyuzaitu@126.com";

boost::thread thread1(boost::bind(&threadFunc, pszContext));

thread1.join();

return 0;

}


3 类的非静态函数作为线程函数

生产环境中经常需要访问类的私有成员,如果类的静态函数作为线程函数,通过参数的方式传递极其不方便

#include <iostream>

#include <string>

#include <boost/thread/thread.hpp>

#include <boost/function/function0.hpp>


class CThreadClass

{

public:


CThreadClass()

{

memset(m_szContext, 0x00, 1024);

}


void ThreadFunc()

{

std::cout << m_szContext << std::endl;

}


void StartThread()

{

strcpy_s(m_szContext, "Welcome to thread func\n");

boost::function0<void> f = boost::bind(&CThreadClass::ThreadFunc, this);

boost::thread thrd(f);

thrd.join();

}


private:


char m_szContext[1024];

};

int main(int argc, char* argv[])

{

CThreadClass instance;

instance.StartThread();

return 0;

}


参考http://blog.csdn.net/zhuxiaoyang2000/article/details/6588031/






    本文转自fengyuzaitu 51CTO博客,原文链接:http://blog.51cto.com/fengyuzaitu/1951940,如需转载请自行联系原作者