-
Notifications
You must be signed in to change notification settings - Fork 2
/
thread.h
81 lines (69 loc) · 1.14 KB
/
thread.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#ifndef _THREAD_H_
#define _THREAD_H_
#include <pthread.h>
class ThreadException
{
};
class Thread
{
public:
Thread();
Thread(void * arg);
~Thread();
virtual void * run(void * arg) = 0;
void start();
void start(void * arg);
void wait();
void stop();
protected:
static void * run_(void * arg);
void * arg_;
pthread_t pid_;
volatile bool stop_;
};
Thread::Thread() : arg_(NULL), stop_(false)
{
}
Thread::Thread(void * arg) : arg_(arg), stop_(false)
{
}
Thread::~Thread()
{
}
void Thread::start()
{
start(arg_);
}
void Thread::start(void * arg)
{
arg_ = arg;
int err = pthread_create(&pid_, NULL, &run_, this);
if (0 != err)
{
throw ThreadException();
}
}
void Thread::wait()
{
void * thread_ret = NULL;
int err = pthread_join(pid_, &thread_ret);
if (0 != err)
{
throw ThreadException();
}
}
void Thread::stop()
{
stop_ = true;
//int err = pthread_cancel(pid_);
//if (0 != err)
//{
// throw ThreadException();
//}
}
void * Thread::run_(void * arg)
{
Thread * t = reinterpret_cast<Thread *>(arg);
return t->run(t->arg_);
}
#endif // _THREAD_H_