[英]Running std::thread with different argument function
is it possible to create N std::thread objects, each running a while loop until the "task" list is not empty ? 是否可以创建N个std :: thread对象,每个对象运行一个while循环,直到“任务”列表不为空?
It could be look like this: 可能看起来像这样:
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
with function declaration: 带有函数声明:
bool func1( int, int, int );
bool func2( int );
bool func3( int );
bool func4( std::string );
is this possible with variadic arguments ? 可变参数可能吗?
This should be pretty simple with std::bind
and std::function
so long as all of the functions have the same return type. 只要所有函数都具有相同的返回类型,这对于std::bind
和std::function
应该非常简单。
In your Schedule
class you can just store a std::queue<std::function<bool()>>
. 在您的Schedule
类中,您可以只存储一个std::queue<std::function<bool()>>
。 Then have Schedule::add()
look something like this: 然后让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()>
}
Then you can add tasks like so: 然后,您可以添加如下任务:
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();
Then just have your worker threads do something like: 然后让您的工作线程执行以下操作:
Schedule::worker() {
// Synchronization left as an exercise for the reader...
while (more_work_to_do) {
std::function<bool()> f(function_queue.pop_back());
f();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.