mercredi 26 juillet 2017

Work Queue: Defining run() Function

I'm making a thread pool / worker queue in C++11 and I am not sure what's the best way to define units of work. Currently I have a base class Job that has an abstract function run().

class AdderJob: public Job
{
    int val1;
    int val2;
    int ret;
    AdderJob( int v1, int v2 ) : val1( v1 ), val2( v2 ) {}
    virtual void run()
    {
        this->ret = val1 + val2;
    }
};

int main( void )
{
    WorkerQueue* queue = WorkerQueue::getQueue();
    AdderJob job( 4, 5 );
    queue->addJob( &job ); // Adds the job to the queue
    int state = queue->getJobState( &job ); // Non-blocking returns state of job : JOB_PENDING, JOB_RUNNING, JOB_FINISHED, JOB_DOES_NOT_EXIST
    queue->waitOnJob( &job ); // Waits for job to finish and removes job from results queue
    std::cout << job.ret << sd::endl; // Returns 4 + 5 = "9".
}

The biggest downside is that I need to derive Job for every unit of work that needs to be done. This can be a little cumbersome.

I am wondering if it would be better for my Job to encapsulate a std::function that is run by the worker queue. This could allow for lightweight code and flexibility (you tell me). However, I'm not entirely sure how to recreate my AdderJob in this system.

Aucun commentaire:

Enregistrer un commentaire