boost 线程 linux,Boost中的function和bind功能,实现Linux下线程类封装

最近在看陈硕的MUDUO网络通讯库的过程当中,发现做者大量使用了Boost::function以及Boost::bind功能,为了可以正常的学习做者的代码,决定先弄明白function以及bind的功能。ios

Boost::Function 是对函数指针的对象化封装,在概念上与广义上的回调函数相似。相对于函数指针,function除了使用自由函数,还可使用函数对象,甚至是类的成员函数,这个就很强大了哈。windows

1. 一个简单的示例代码

#include

#include

#include

using namespace std;

class TestA

{

public:

void method()

{

cout<

}

void method(int a, int b)

{

cout<

<

<

}

};

void sum(int a, int b)

{

int sum = a + b;

cout<

}

int main()

{

boost::function f;

TestA test;

f = boost::bind(&TestA::method, &test);

f();

f = boost::bind(&TestA::method, &test, 1, 2);

f();

f = boost::bind(&sum, 1, 2);

f();

}

输出结果:

Administrator@8bd5ec9e02074bf ~/source

$ ./BoostFunction.exe

TestA: method: no arguments

TestA: method: with argumentsvalue of a is:1value of b is 2

sum: 3

2. 应用:Thread封装

在实现自定义的线程类时,曾经这么干过:定义虚函数run(),用户自定义的CustomThread::Thread后,本身实现run()函数就OK了。 当时以为这么作也不错。

如今有了boost::function/boost::bind咱们能够这么干:

定义一个线程类:

.h文件网络

#include

#include

#include

#include

using namespace std;

class Thread

{

typedef boost::function ThreadFun;

public:

Thread(const ThreadFun& threadFun,const string& threadName = string());

pid_t     getThreadId();

string getThreadName();

int       start();

private:

static void* startThread(void* thread);

private:

pthread_tm_thread; //线程句柄

pid_tm_tid;    //线程ID

stringm_strThreadName;    //线程名称

boolm_bStarted;         //线程是否启动

ThreadFunm_func;             //线程处理函数

};

.cpp文件函数

#include "thread.h"

Thread::Thread(const Thread::ThreadFun& threadFun, const string& threadName):

m_func(threadFun), m_strThreadName(threadName)

{

}

int Thread::start()

{

m_tid = pthread_create(&m_thread, NULL, &startThread, this);

return 0;

}

void* Thread::startThread(void* obj)

{

Thread* thread = static_cast(obj);

thread->m_func();

return NULL;

}

pid_t Thread::getThreadId()

{

return m_tid;

};

stringThread::getThreadName()

{

return m_strThreadName;

}

测试程序学习

void ThreadProcess()

{

int count = 100;

for (int i = 0; i < count; i++)

{

if (i % 10 == 0)

cout<

cout<

}

}

int main()

{

boost::function f;

f = boost::bind(&ThreadProcess);

Thread thread(f, "ThreadTest");

thread.start();

sleep(1000*1000);

return 0;

}

输出结果(Cygwin):

9ff5b80647b64664aa80e54b.html

>根据上述程序,咱们能够发现,这样咱们就不须要定义不少不少的类去继承Thread类,而只须要写好线程运行函数,set到Thread类中便可。不过也不能说利用虚函数留接口给用户实现就很差,只不过如今多了一种方法。(陈硕很反对用虚函数做为结构提供给用户去作实现,可是我如今尚未切身的体会以为那里很差)

3. 总结

注:

1. 这边只是简单的用boost::function/bind结合pthread简单的实现了一个本身封装的线程类,

2. boost::function/bind还有不少其余高级用法,我这边只是用来当作一个函数指针用了哈this

3. 测试环境:cygwin

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值