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
|
#include <type_traits>
#include <memory>
#include <queue>
#include <iostream>
struct job
{
virtual ~job() {}
bool completed() const { return done ; }
void run() { do_run() ; done = true ; }
protected : virtual void do_run() = 0 ;
private: bool done = false ;
} ;
struct my_work_queue
{
template< typename T, typename... CONSTRUCTOR_ARGS >
typename std::enable_if< std::is_base_of<job,T>::value, std::shared_ptr<job> >::type
queue_job( CONSTRUCTOR_ARGS... args )
{
auto pjob = std::make_shared<T>(args...) ;
q.push(pjob) ;
return pjob ;
}
void execute_job()
{
if( !q.empty() )
{
q.front()->run() ;
q.pop() ;
}
}
void execute_all() { while( !q.empty() ) execute_job() ; }
private: std::queue< std::shared_ptr<job> > q ;
};
int main()
{
struct job_one : job
{
virtual ~job_one() { std::cout << "job_one::destructor\n" ; }
protected: virtual void do_run() override { std::cout << "job_one::run\n" ; }
} ;
struct job_two : job
{
job_two( int aa, int bb = 99, double cc = -23.9 ) : a(aa), b(bb), c(cc) {}
virtual ~job_two()
{ std::cout << "job_two{ " << a << ", " << b << ", " << c << " }::destructor\n" ; }
protected: virtual void do_run() override
{ std::cout << "job_two{ " << a << ", " << b << ", " << c << " }::run\n" ; }
private:
int a, b ;
double c ;
} ;
my_work_queue wq ;
wq.queue_job<job_one>() ;
auto p = wq.queue_job<job_two>(5) ;
wq.queue_job<job_two>( 5, 6 ) ;
wq.queue_job<job_two>( 5, 6, 7.8 ) ;
std::cout << std::boolalpha << p->completed() << '\n' ;
wq.execute_all() ;
std::cout << "----------\n" << p->completed() << '\n' ;
}
|