码迷,mamicode.com
首页 > 系统相关 > 详细

Linux组件封装(三) Thread的封装

时间:2014-10-06 23:06:30      阅读:225      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   os   使用   ar   strong   sp   

声明代码如下:

 1 #ifndef THREAD_H
 2 #define THREAD_H
 3 
 4 #include "NonCopyable.h"
 5 #include <pthread.h>
 6 #include <sys/types.h>
 7 
 8 class Thread : NonCopyable
 9 {
10 public:
11     Thread();
12     ~Thread();
13 
14     void start();
15     void join();
16 
17     pthread_t getThreadId() { return _threadId; }
18     virtual void run()=0;
19 
20 private:
21     static void *func(void *arg);
22 
23     pthread_t _threadId;
24     bool _isRun;
25 };
26 
27 #endif

为了调用pthread_create创建线程,我们往里面注册的不能是一个成员函数,因为成员函数含有一个隐式参数,导致函数的指针类型并不是void *(*start_routine) (void *),所以我们采用了static函数

static函数无法访问某一对象的成员,所以我们在调用pthread_create时,将this指针作为回调函数的参数

这个Thread不提供detach函数,因为我们在析构函数中做了如下的处理,如果Thread对象析构,线程还在运行,那么需要将Thread设置为detach状态

大部分逻辑都是固定的,用户只需要改变run里面的代码即可,于是我们将run设置为纯虚函数,让用户继承Thread类

cpp代码实现如下:

 1 #include "Thread.h"
 2 #include <iostream>
 3 #include <assert.h>
 4 #include <unistd.h>
 5 #include <pthread.h>
 6 #include <sys/syscall.h>
 7 using namespace std;
 8 
 9 Thread::Thread()
10     :_threadId(0),
11      _isRun(false)
12 { }
13 
14 Thread::~Thread()
15 {
16     if(_isRun)
17         pthread_detach(_threadId);
18 }
19 
20 
21 void *Thread::func(void *arg)
22 {
23     Thread *p = static_cast<Thread *>(arg);
24     p->run();
25     return NULL;
26 }
27 
28 
29 void Thread::start()
30 {
31     pthread_create(&_threadId, NULL, Thread::func, this);
32     _isRun = true;
33 }
34 
35 void Thread::join()
36 {
37     assert(_isRun);
38     pthread_join(_threadId, NULL);
39     _isRun = false;
40 }

我们采用继承的方式使用这个类。测试代码如下:

 1 #include "Thread.h"
 2 #include <iostream>
 3 #include <unistd.h>
 4 using namespace std;
 5 
 6 class MyThread : public Thread
 7 {
 8 public:
 9     void run()
10     {
11         cout << "foo" << endl;
12     }
13 };
14 
15 int main(int argc, char const *argv[])
16 {
17     MyThread t;
18     t.start();
19 
20     t.join();
21 
22     return 0;
23 }

 

Linux组件封装(三) Thread的封装

标签:style   blog   color   io   os   使用   ar   strong   sp   

原文地址:http://www.cnblogs.com/gjn135120/p/4008690.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!