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

本文提供了Boost线程库的基本使用示例,包括简单的线程启动、带参数的线程函数及类成员函数作为线程任务的方法。

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.youkuaiyun.com/zhuxiaoyang2000/article/details/6588031/






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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值