使用不同的参数函数运行std :: thread

时间:2015-07-15 05:22:17

标签: c++ multithreading c++11

是否可以创建N个std :: thread对象,每个对象运行一个while循环,直到“task”列表不为空?

可能看起来像这样:

Schedule sched( N );
schned.add( func1, param1, param2, param3 );
schned.add( func1, param1, param2, param3 );

schned.add( func2, param1 );

schned.add( func3, IntegerParam );
schned.add( func4, StringParam );

sched.start(); // start & join each thread wait until all threads finished

带功能声明:

bool func1( int, int, int );
bool func2( int );
bool func3( int );
bool func4( std::string );

这可能是variadic arguments吗?

1 个答案:

答案 0 :(得分:3)

对于std::bindstd::function,只要所有函数都具有相同的返回类型,这应该非常简单。

Schedule课程中,您只需存储std::queue<std::function<bool()>>。然后让Schedule::add()看起来像这样:

template<typename func>
Schedule::add(func f) {
    // Appropriate synchronization goes here...
    function_queue.push_front(f);  // Will work as long as func can be converted to std::function<bool()>
}

然后你可以像这样添加任务:

Shedule sched(N);
// This works with function pointers
sched.add(someFunctionThatTakesNoArgs);
// And function like objects such as those returned by std::bind
sched.add(std::bind(func1, param1, param2, param3));
sched.add(std::bind(func1, param1, param2, param3));
sched.add(std::bind(func2, param1));
// Even member functions
SomeClass foo;
sched.add(std::bind(SomeClass::func3, foo, IntegerParam));
sched.add(std::bind(SomeClass::func4, foo, StringParam));

sched.start();

然后让你的工作线程做类似的事情:

Schedule::worker() {
    // Synchronization left as an exercise for the reader...
    while (more_work_to_do) {
        std::function<bool()> f(function_queue.pop_back());
        f();
    }
}