-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTM.cpp
More file actions
97 lines (80 loc) · 1.89 KB
/
Copy pathTM.cpp
File metadata and controls
97 lines (80 loc) · 1.89 KB
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
#include "TM.h"
using namespace std;
/* delcare static member in other ThreadManager.h */
//pthread_mutex_t ThreadManager::mutex0, ThreadManager::mutex1;
//int ThreadManager::running;
void* wrapper(void* param)
{
ThreadManager* t = (ThreadManager*)param;
t->worker();
return NULL;
}
Job::Job(void *(*t)(void*) = NULL, void *a = NULL):task(t), arg(a) {}
ThreadManager::ThreadManager (int size) {
running = true;
running_jobs = 0;
thread_num = size;
pthread_mutex_init(&mutex0, NULL);
pthread_mutex_init(&mutex1, NULL);
pthread_mutex_init(&mutex2, NULL);
threads = new pthread_t[size];
for (int i = 0;i < size;i++) {
int rc = pthread_create(&threads[i], NULL, wrapper, (void*)this);
assert(rc == 0);
}
}
ThreadManager::~ThreadManager () {
if (running) {
running = false;
sync();
}
pthread_mutex_destroy(&mutex0);
pthread_mutex_destroy(&mutex1);
pthread_mutex_destroy(&mutex2);
delete []threads;
}
void ThreadManager::sync()
{
//printf("running_jobs = %d\n", running_jobs);
while (running_jobs > 0) { usleep(10); }
running = false;
for (int i = 0;i < thread_num;i++) {
pthread_join(threads[i], NULL);
}
}
int ThreadManager::size()
{
return running_jobs;
}
void ThreadManager::worker()
{
while (running) {
int rc = pthread_mutex_trylock(&mutex0);
if (!rc) {
Job ajob;
if (jobs.size() > 0) {
ajob = jobs.front();
jobs.pop();
}
pthread_mutex_unlock(&mutex0);
if (ajob.task) { //succ acquire a Job
ajob.task(ajob.arg);
pthread_mutex_lock(&mutex2);
running_jobs --;
pthread_mutex_unlock(&mutex2);
}
}else { usleep(1); }
usleep(1);
}
}
int ThreadManager::append(void *(*task)(void*), void *real)
{
while (jobs.size() > 10000) { usleep(1); }
pthread_mutex_lock(&mutex0);
jobs.push(Job(task, real));
pthread_mutex_unlock(&mutex0);
pthread_mutex_lock(&mutex2);
running_jobs ++;
pthread_mutex_unlock(&mutex2);
return true;
}