/* * Worker.hh * * Created on: 20 janv. 2013 * Author: taz */ #ifndef WORKER_HH_ #define WORKER_HH_ #include #include #include "CThreadDeque.hh" namespace AMDA { namespace Helpers { namespace base { struct Task { virtual ~Task() {} virtual void operator()() = 0; }; } template 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 getFuture() { return _promise.get_future(); } private: Func _func; boost::promise _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 _taskList; bool _running; boost::thread _thread; }; } /* namespace Helpers */ } /* namespace AMDA */ #endif /* WORKER_HH_ */