基于对象风格的编程思想和面向对象的编程思想不同。面向对象使用纯虚函数为派生类提抽象接口,是一种抽象类(实现回调);而基于对象使用具体类,在类里面通过注册函数实现回调;若是C风格的编程思想,则是定义全局的注册函数指针。
基于对象风格的线程类封装代码如下:
类头文件:
//start from the very beginning,and to create greatness
//@author: Chuangwei Lin
//@E-mail:979951191@qq.com
//@brief: 基于对象风格的线程类封装
#include <pthread.h>
#include <iostream>
#include <boost/function.hpp>
#include <boost/bind.hpp>
#ifndef _LCW_THREAD_H_
#define _LCW_THREAD_H_
//线程基类
class lcw_thread
{
public:
//重定义新类型
typedef boost::function<void ()> LCW_Function;
//构造函数,关键字explicit使其只能显式调用
explicit lcw_thread(const LCW_Function& func);
~lcw_thread();//析构函数
void Start();
void Join();
void SetAutoDelete(bool AutoDelete);
private:
static void* Thread_Routine(void* arg);
void Run();
LCW_Function func_;
pthread_t lcwid;
bool AutoDelete;//是否自动销毁
};
#endif
类实现函数:
//start from the very beginning,and to create greatness
//@author: Chuangwei Lin
//@E-mail:979951191@qq.com
//@brief: 基于对象风格的线程类封装
#include "lcw_thread.h"
using namespace std;
lcw_thread::lcw_thread(const LCW_Function& func) :func_(func) ,AutoDelete(false)
{
cout << "构造函数lcw_thread" << endl;
}
lcw_thread::~lcw_thread()
{
cout << "析构函数lcw_thread" << endl;
}
void lcw_thread::Start()//启动线程
{
pthread_create(&lcwid,NULL,Thread_Routine,this);//this指针是参数
}
void lcw_thread::Join()
{//函数pthread_join用来等待一个线程的结束
pthread_join(lcwid,NULL);
}
void* lcw_thread::Thread_Routine(void* arg)
{//参数arg其实是this指针
lcw_thread* lcwthread = static_cast<lcw_thread*>(arg);//指向派生类指针转化为基类对象指针
lcwthread->Run();
if(lcwthread->AutoDelete)//
{
delete lcwthread;//销毁线程
}
return NULL;
}
void lcw_thread::SetAutoDelete(bool AutoDelete_)
{
AutoDelete = AutoDelete_;//设置是否自动销毁
}
void lcw_thread::Run()
{
func_();
}
回调函数和测试函数:
//start from the very beginning,and to create greatness
//@author: Chuangwei Lin
//@E-mail:979951191@qq.com
//@brief: 基于对象风格的线程类封装
#include "lcw_thread.h"
#include <unistd.h>
using namespace std;
//线程回调函数
void lcw1()
{
cout << "lcw1回调" << endl;
}
void lcw2(int count)
{
for(int i = 1;i <= count;i++)
{
cout << "lcw2第"<< i << "次调用" <<endl;
}
}
int main(int argc, char const *argv[])
{
//创建线程,lcw为初始化函数
lcw_thread t1(lcw1);
lcw_thread t2(boost::bind(lcw2,5));
t1.Start();
t2.Start();
t1.Join();
t2.Join();
return 0;
}
运行结果如下: