-
Notifications
You must be signed in to change notification settings - Fork 2
/
Thread.h
111 lines (92 loc) · 1.42 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#pragma once
#include <pthread.h>
#include <semaphore.h>
/**
* Encapsulates a thread and contains methods for starting and stopping one.
*/
class Thread
{
public:
Thread() : running_(false)
{ /* Empty */ }
~Thread()
{
kill();
}
void run( void* f(void*), void * arg)
{
pthread_create(&t_, NULL, f, arg);
running_ = true;
}
void join()
{
if (running_)
pthread_join(t_, NULL);
running_ = false;
}
void kill()
{
if (running_)
{
pthread_cancel(t_);
pthread_join(t_, NULL);
}
running_ = false;
}
private:
bool running_;
pthread_t t_;
};
/**
* Encapsulates a mutex.
*/
class Mutex
{
public:
Mutex()
{
pthread_mutex_init(&m_, NULL);
}
~Mutex()
{
pthread_mutex_destroy(&m_);
}
void lock()
{
pthread_mutex_lock(&m_);
}
void unlock()
{
pthread_mutex_unlock(&m_);
}
private:
pthread_mutex_t m_;
};
class Semaphore
{
public:
Semaphore(int value = 0)
{
sem_init(&sem_, 0, value);
}
~Semaphore()
{
sem_destroy(&sem_);
}
void inc()
{
sem_post(&sem_);
}
void dec()
{
sem_wait(&sem_);
}
int value()
{
int ret;
sem_getvalue(&sem_, &ret);
return ret;
}
private:
sem_t sem_;
};