-
Notifications
You must be signed in to change notification settings - Fork 11
/
ciThread.h
106 lines (94 loc) · 2.31 KB
/
ciThread.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
#pragma once
#include <pthread.h>
class ciThread {
public:
ciThread() {
threadRunning = false;
verbose = false;
pthread_mutex_init(&myMutex, NULL);
}
virtual void unload() {
stopThread();
}
bool isRunning() {
return threadRunning;
}
void startThread(bool _blocking = true, bool _verbose = true) {
if(threadRunning) {
if(verbose) {printf("Thread already running.\n");}
return;
}
threadRunning = true;
pthread_create(&myThread, NULL, thread, (void *)this);
blocking = _blocking;
verbose = _verbose;
}
bool lock() {
if(blocking){
if(verbose) {printf("Waiting for mutex to unlock...\n");}
pthread_mutex_lock(&myMutex);
if(verbose) {printf("Mutex locked.\n");}
}
else{
int value = pthread_mutex_trylock(&myMutex);
if(value == 0) {
if(verbose) {printf("Mutex locked.\n");}
}
else {
if(verbose) {printf("Mutex is busy.\n");}
return false;
}
}
return true;
}
bool unlock() {
pthread_mutex_unlock(&myMutex);
if(verbose) {printf("Mutex unlocked.\n");}
return true;
}
void stopThread(bool close = true) {
if(threadRunning) {
if(close) {
pthread_detach(myThread);
}
if(verbose) {printf("Thread stopped.\n");}
threadRunning = false;
}
else {
if(verbose) {printf("Thread already stopped.\n");}
}
}
void wait(bool stop = true) {
if(threadRunning) {
// Reset the thread state
if(stop){
threadRunning = false;
if(verbose) {printf("Stopping thread...\n");}
}
if(verbose) {printf("Waiting for thread to stop...\n");}
if(pthread_self()==myThread) {printf("Wait cannot be called from within thread.\n");}
pthread_join(myThread, NULL);
if(verbose) {printf("Thread stopped.\n");}
myThread = NULL;
}
else{
if(verbose) {printf("Thread already stopped.\n");}
}
}
protected:
virtual void threadedFunction() {
if(verbose) {printf("Overload this function.\n");}
}
static void * thread(void * objPtr) {
ciThread* me = (ciThread*)objPtr;
me->threadedFunction();
me->stopThread(false);
pthread_exit(NULL);
return 0;
}
pthread_t myThread;
pthread_mutex_t myMutex;
bool threadRunning;
bool blocking;
bool verbose;
};