线程类基本封装

线程类


面向对象风格:
通过子类重写run方法 实现多态 从而实现依赖反转
但我们要提供抽象类和接口


将run()方法和startThread()方法声明的私有的 其实本没有有必要声明为公有的 我们在start------>startThread ---->run
class Thread
{
Thread();
virtual ~Thread();
void start();
void join();

private:
static void* startThread(void *arg);
virtual void run() = 0;
pthread_t pthread_id;
};


//为什么不直接将函数的run方法直接作为入口函数 (会隐含传递this指针 不符合pthread_create线程入口函数的定义 )
//解决方案 定义一个全局的函数 但为了不让外界能直击访问 定义为类的静态成员 在该函数里面调用run方法
//但是类得静态成员函数是无法访问类的非静态成员或者函数的 因此我们在传递参数的时候需要将this指针传递进来 才能调用类的run方法


void Thread::start()
{
pthread_cretae(&pthread_id, NULL, startThread, this);
}


void* startThread(void *arg)
{
Thread* thread = (Thread*)arg;
thread->run();
return NULL;
}


基于对象的编程风格:
利用boost下的function和bind函数实现
#include <boost/function.hpp>


typedef boost::function<void ()>  ThreadFunc;


class Thread
{
public:
Thread(ThreadFunc thread_fun);
~Thread();
void start();
void join();
private:
static void* startThread(void *arg);
void run();
ThreadFunc thread_fun_;
pthread_t pthread_id;
};


Thread::Thread(ThreadFunc thread_fun):thread_func_(thread_fun)
{


}


void Thread::start()
{
pthread_create(&pthread_id, NULL, run, NULL);
}


void* startThread(void *arg)
{
Thread* thread = (Thread*)arg;
thread->run();
return NULL;
}


void Thread::run()
{
thread_fun_();
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值