基于对象风格的线程类封装
来源:互联网 发布:淘宝店铺管理方案 编辑:程序博客网 时间:2024/06/01 08:40
基于对象风格的编程思想和面向对象的编程思想不同。面向对象使用纯虚函数为派生类提抽象接口,是一种抽象类(实现回调);而基于对象使用具体类,在类里面通过注册函数实现回调;若是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;}
运行结果如下:
1 0
- 基于对象风格的线程类封装
- 面向对象风格的线程类封装
- 基于任务的线程封装
- c++类和类的封装,对象线程封装
- 面向对象的风格和基于对象的风格程序设计
- C++中面向对象和基于对象的线程封装方法
- 实现线程的封装, 2种方式(面向对象,基于对象)
- c++基于对象的编程风格
- c++基于对象的编程风格2
- 基于AsyncTask的线程池封装
- 基于面向对象封装的模态对话框类
- 一个MFC风格的BrowseForFolder 封装类
- lua 封装成C++风格的类
- lua 封装成C++风格的类
- linux开发:线程的面向对象封装
- linux C++ 面向对象线程类封装
- linux C++ 面向对象线程类封装
- linux C++ 面向对象线程类封装
- php_array
- yum 变量
- mysql的多实例multi启动停止
- MySQL 通过bat命令备份windows下的mysql数据库
- 解决MySQL导入备份文件到新数据库乱码问题
- 基于对象风格的线程类封装
- WSUS pentest white paper
- linux_svn权限中配置的文件
- Android触控基础:属性详解
- 有关MySQL的数据库规范与日常经验
- read 系统调用剖析
- android Dialog 宽是否占满
- JavaWeb 中文乱码
- select,poll,epoll区别