-
Notifications
You must be signed in to change notification settings - Fork 14
/
ThreadPool.h
79 lines (54 loc) · 1.29 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
/*
* A thread pool implementation.
*
* Author: Martin Schobert <schobert@sitsec.net>
*
*/
#ifndef __THREADPOOL_H__
#define __THREADPOOL_H__
#include <boost/thread.hpp>
#include <boost/function.hpp>
#include <boost/foreach.hpp>
#include <iostream>
#include <tr1/memory>
template <typename FunctionType>
class ThreadPool {
typedef std::tr1::shared_ptr<boost::thread> thread_shptr;
private:
unsigned int max_n;
std::list<FunctionType> task_queue;
std::list<thread_shptr> running;
void spawn() {
while(running.size() < max_n && task_queue.size() > 0 ) {
FunctionType f(task_queue.front());
task_queue.pop_front();
boost::thread * p = new boost::thread(f);
thread_shptr t = thread_shptr(p);
running.push_back(t);
}
}
public:
ThreadPool(unsigned int n = 4) : max_n(n) {
}
~ThreadPool() {
wait();
}
void add(FunctionType f) {
task_queue.push_back(f);
}
void wait() {
while(task_queue.size() > 0 || running.size() > 0) {
spawn();
for(std::list<thread_shptr>::iterator iter = running.begin();
iter != running.end(); ++iter) {
//std::cout << "timed wait\n";
if((*iter)->timed_join(boost::posix_time::millisec( 1000 ) )) {
std::list<thread_shptr>::iterator i(iter);
++iter;
running.erase(i);
}
}
}
}
};
#endif