Worker.hh
1.37 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
/*
* Worker.hh
*
* Created on: 20 janv. 2013
* Author: taz
*/
#ifndef WORKER_HH_
#define WORKER_HH_
#include <boost/thread/thread.hpp>
#include <boost/thread/future.hpp>
#include "CThreadDeque.hh"
namespace AMDA {
namespace Helpers {
namespace base {
struct Task {
virtual ~Task() {}
virtual void operator()() = 0;
};
}
template <typename Result>
class Task : public base::Task {
public:
typedef boost::function< Result ()> Func;
Task(Func func) : _func(func) {}
void operator()() {try {
_promise.set_value(_func());
} catch(...) {
_promise.set_exception(boost::current_exception());
}
}
boost::unique_future<Result> getFuture() { return _promise.get_future(); }
private:
Func _func;
boost::promise<Result> _promise;
};
class Worker {
public:
Worker();
virtual ~Worker();
void active() {
if(!_thread.joinable()) {
_running = true;
_thread = boost::thread(boost::bind(&Worker::taskLoop,this));
}
}
protected:
void taskLoop() {
//Execute Task
base::Task* task = NULL;
do {
if ( (task = _taskList.pop_timedwait( 60, task))) {
(*task)();
delete task;
task = NULL;
}
} while( _running);
}
protected:
CThreadDeque<base::Task*> _taskList;
bool _running;
boost::thread _thread;
};
} /* namespace Helpers */
} /* namespace AMDA */
#endif /* WORKER_HH_ */