[英]Running std::thread with different argument function
是否可以創建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 );
可變參數可能嗎?
只要所有函數都具有相同的返回類型,這對於std::bind
和std::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();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.