多线程Thread类不同封装实现
来源:互联网 发布:菲律宾程序员招聘骗局 编辑:程序博客网 时间:2024/05/20 01:09
- 多线程Thread类实现
1.C语言实现方式:通过建立多个全局线程回调函数实现
2.面向对象实现方式:通过多态特性实现,虚函数在派生类中不同的行为方式
3.基于对象实现方式:通过boost::function和bind实现 - - 对于Linux线程创建方式:
int pthread_create(pthread_t *restrict thread, const pthread_attr_t *restrict attr, void *(*start_routine)(void*), void *restrict arg);
参数1.线程ID
参数2.线程属性
参数3.线程回调函数
参数4.回调函数
C语言实现线程方式:
通过建立全局线程回调函数实现,对于多个线程多个 不同任务需要建立多个全局函数,例子
void threadFunction1(void* arg){ printf("child thread 1\n"); pthread_exit(NULL);}void threadFunction2(void* arg){ printf("child thread 2\n"); pthread_exit(NULL);}int main(){ pthread_t thread1; pthread_t thread2; pthread_create(&thread1,NULL,threadFunction1,NULL); pthread_create(&thread2,NULL,threadFunction2,NULL); pthread_join(thread1,NULL); pthread_join(thread2,NULL); return 0;}
面向对象封装方式
虚函数在派生类中不同的行为方式
class Thread{public: Thread(){} virtual ~Thread(){} void start() { pthread_create(&_thread,NULL,thread_rountine,this); } void join() { pthread_join(_thread,NULL); }private:static void* thread_rountine(void* arg){ // 不同的线程调用同样的thread_rountine函数,this指针指向不同的线程派生类,执行派生类中的run行为 Thread* thread = static_cast<Thread*>(arg); thread->run(); return NULL;}virtual run()=0;pthread_t _thread;};
在prthread_create中为什么不能传递类的成员函数,使用静态的成员函数,因为pthread_create的参数三是一个普通的函数,而类的成员函数隐含传递一个this指针。
3. 基于对象封装方式(muduo库实现方式 boost::function/bind)
通过boost::function和bind实现
class Thread{public: typedef boost::function<void ()> ThreadFunc; explicit Thread(const ThreadFunc& func):_func(func){} ~Thread(){} void start(){pthread_create(&_thread,NULL,thread_rountine,this);} void join(){pthread_join(_thread,NULL);}private: ThreadFunc _func; pthread_t _thread; void run() { _func(); } static void* thread_rountine(void* arg) { // boost::function类似于一种函数指针的声明,boost::bind类似于绑定一个函数 // 对于不同线程执行不同的行为时,只需要通过boost::bind改变即可实现。 Thread* thread = static_cast<Thread*>(arg); thread->run(); return NULL;}};class Foo{public:void MemberFun(){ cout<<"child thread1"<<endl;}void MemberFun1(int count){ cout<<"child thread2:"<<count<<endl;}};int main(){ Foo foo1(); Foo foo2(); Thread t(boost::bind(&Foo::MemberFun, &foo)); Thread t1(boost::bind(&Foo::MemberFun1,&foo2,3));}
两种方式比较
个人观点:
继承实现的方式耦合性强,当功能扩展时,都需要建立新的派生类实现run方法
对于基于对象方式来说,耦合性低,对于功能扩展只需要编写一个函数就可以了,扩展性强
阅读全文
0 0
- 多线程Thread类不同封装实现
- java Thread:利用Thread类实现多线程
- 多线程实现(Thread类)
- Linux thread 封装实现
- Thread- 扩展java.lang.Thread类,实现多线程
- Java通过继承Thread类实现多线程
- 继承Thread类来实现多线程
- 通过继承Thread类实现多线程
- 通过继承Thread类实现多线程
- java 通过继承 Thread 类实现多线程
- 【多线程】JAVA——Thread类实现
- 多线程-利用thread类和runnable接口实现多线程
- Java多线程—创建Thread类实现多线程
- Thread类封装
- java 通过Thread实现多线程
- Python:继承Thread实现多线程
- 多线程实现及Java Thread
- java多线程:1、Thread实现
- Eclipse+Intellij IDEA创建Maven项目
- Python温度转换实例
- 模板--最小生成树【prim】
- 一些深度学习网络精确率、大小的比较
- 推荐一个不错的bootstrap中文系列学习教程网站-狗鱼IT教程
- 多线程Thread类不同封装实现
- servlet
- mysql学习2—外键约束的参照操作
- [Js] Js实现继承的5种方式
- forward
- I am here!
- C/C++一些特殊关键字的作用&指针和引用的区别
- Excel 技巧百例:数据透视表的简单使用-行列转换
- (十三)QQ 消息气泡