-
Notifications
You must be signed in to change notification settings - Fork 4
/
ThreadPool.h
79 lines (59 loc) · 1.5 KB
/
ThreadPool.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
#ifndef THREADPOOL_H
#define THREADPOOL_H
#include "lzopfs.h"
#include <queue>
#include <pthread.h>
class Mutex {
protected:
pthread_mutex_t mMutex;
public:
Mutex() { pthread_mutex_init(&mMutex, 0); }
~Mutex() { pthread_mutex_destroy(&mMutex); }
void lock() { pthread_mutex_lock(&mMutex); }
void unlock() { pthread_mutex_unlock(&mMutex); };
};
class Lock {
Mutex& mMutex;
public:
Lock(Mutex& m) : mMutex(m) { mMutex.lock(); }
~Lock() { mMutex.unlock(); }
};
class ConditionVariable : public Mutex {
pthread_cond_t mCond;
public:
ConditionVariable() { pthread_cond_init(&mCond, 0); }
~ConditionVariable() { pthread_cond_destroy(&mCond); }
void wait() { pthread_cond_wait(&mCond, &mMutex); }
void signal() { pthread_cond_signal(&mCond); }
void broadcast() { pthread_cond_broadcast(&mCond); }
};
class ThreadPool {
public:
struct Job {
virtual void operator()() = 0;
virtual ~Job() { }
};
protected:
struct ThreadInfo {
ThreadPool *pool;
pthread_t pthread;
size_t num;
ThreadInfo(ThreadPool *p = 0, size_t n = 0) : pool(p), num(n) { }
};
typedef std::vector<ThreadInfo> ThreadList;
ThreadList mThreads;
ConditionVariable mCond;
// Consider differentiating between queued and in-progress jobs, so we can
// deduplicate jobs.
typedef std::queue<Job*> JobQ;
JobQ mJobs;
bool mCancelling;
size_t systemCPUs() const;
Job *nextJob();
static void *threadFunc(void *val);
public:
ThreadPool(size_t threads = 0);
~ThreadPool();
void enqueue(Job* job);
};
#endif // THREADPOOL_H