用“任务”功能指针队列定义作业管理器

时间:2018-10-28 15:50:06

标签: c++ c++11

我正在制作一个具有工作线程线程池的作业管理器,并且每个工作线程将从队列中拉出并执行给定的作业(如果有)。

我正在苦苦挣扎的实际上是调用我存储在并发队列中的函数指针。

我已经定义了一个CpuJob结构,如下所示:

class ITask {};  // An interface that should be inherited 
                 // from if you want your class to be "Jobified" 

typedef void ( ITask::*task_func )( void*, int ); // A job function 
                                                  // MUST take a void* and an int 

struct CpuJob
{
    task_func task_func_ptr;

    void* args = nullptr;

    int index = 0;
};

这是我的AddJob函数:

 void Jobs::JobManager::AddJob_Member( task_func aJob, void * aArgs, int aIndex )
 {
     CpuJob temp = {};
     temp.task_func_ptr = aJob;
     temp.args = aArgs;
     temp.index = aIndex;

     readyQueue.emplace_back( temp );    // This is a wrapper around std::queue to be concurrent and thread safe

     jobAvailableCondition.notify_one();

 }

在我的工作线程中,我想调用存储函数指针的地方,是我得到错误的地方:

 // Other stuff popping jobs off the queue
 if ( !readyQueue.empty() )
 {
     CpuJob CurJob;
     readyQueue.pop_front( CurJob );

     CurJob.task_func_ptr( CurJob.args, CurJob.index );  // This is giving me an error 

        // Notify other threads that a job has been taken and we should probably
        // check to make sure that there isn;t more
        jobAvailableCondition.notify_one();
    }

我得到的错误如下:

Error (active) expression preceding parentheses of apparent call must have (pointer-to-) function type

我认为这与我引用该函数的方式有关,但是我尝试了几种方法都无济于事。

1 个答案:

答案 0 :(得分:0)

task_func是成员函数(typedef void (ITask::*task_func)( void*, int);)的指针。
调用它时,您必须指定它在哪个对象上运行,例如(some_object.*my_task_func)(some_args, some_index);

我的建议:不要传递成员函数。有多种选择,例如std::functionstd::bind,指向常规函数的指针和具有虚拟函数的类层次结构。

在C ++常见问题解答的Pointers to Member Function部分中对此进行了详细说明。

相关问题