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

罗比

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

可能看起来像这样:

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 );

可变参数的说法有可能吗?

迈尔斯·布德奈克(Miles Budnek)

这应该是用非常简单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();
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章