-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy paththread.cpp
47 lines (37 loc) · 971 Bytes
/
thread.cpp
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
#include <thread.h>
#include <utils.h>
static void *kickoff(void *arg) {
((Thread*)arg)->run();
return NULL;
}
Thread::Thread() {
if(pthread_mutex_init(&mutex,NULL) == -1)
E("error initializing thread mutex");
if(pthread_attr_init(&attr) == -1)
E("error initializing thread attribute");
pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_JOINABLE);
running = false;
quit = false;
}
Thread::~Thread() {
if(pthread_mutex_destroy(&mutex) == -1)
E("error destroying thread mutex");
if(pthread_attr_destroy(&attr) == -1)
E("error destroying thread attribute");
}
bool Thread::launch() {
lock(); // the runner will unlock when ready
return pthread_create(&thread,&attr,&kickoff, this);
lock(); // wait until the thread is ready
running = true;
unlock();
}
void Thread::lock() {
pthread_mutex_lock(&mutex);
}
void Thread::unlock() {
pthread_mutex_unlock(&mutex);
}
void Thread::join() {
pthread_join(thread,NULL);
}