C++ c++;使用asycron返回的boost线程组
我正在尝试编写一个函数来处理线程组中的线程的输入参数和返回值 我的示例类:C++ c++;使用asycron返回的boost线程组,c++,multithreading,boost,boost-thread,C++,Multithreading,Boost,Boost Thread,我正在尝试编写一个函数来处理线程组中的线程的输入参数和返回值 我的示例类: // includes... class MyClass(int id) { thread_id = id; i = id* 5; b = false; } void resetCounter(int j){ i = j * 5; } int getId(){ return id; } bool getBool(){ return b; } void DoWork(){ wh
// includes...
class MyClass(int id)
{
thread_id = id;
i = id* 5;
b = false;
}
void resetCounter(int j){
i = j * 5;
}
int getId(){
return id;
}
bool getBool(){
return b;
}
void DoWork(){
while( i > 0 ){
boost::this_thread::sleep(boost::posix_time::seconds(i));
i--;
}
b = true; // DoWork will in the real code be able to return false!
}
private:
bool b;
int i;
int thread_id
};
boost::threadgroup threads;
示例代码:
bool exist = false;
for(int i=0;i<4;i++){
// first check if thread id exist (possible)?
// If so don´t create a new thread but reset the counter!
if(exist){
// in current thread call reset "i" (w.resetCounter(i))
}else{
MyClass m(i);
boost::function<void()> thread_func = boost::bind(&MyClass::DoWork, &m);
threads.create_thread(thread_func);
}
}
boolexist=false;
对于(int i=0;i首先,用<代码> thRead组< /Cord>)不能对线程对象进行迭代。因此,如果这是您想要的,考虑将线程对象存储在其他容器中。
此外,您不能移植到等待一个线程完成,但是如果您不介意使用Windows特定的API,您可以使用WaitForMultipleObjects
来实现这一点
但是,我建议您重新设计应用程序,以避免此类把戏。问题到底是什么?我想实现此伪代码,但不确定如何实现。实际上有多个问题。最重要的是如何使一个线程在完成后等待一秒,等待其他线程完成。然后收集一组伪代码在那一秒钟内完成的“线程ID:s”:但仅当“DoWork”返回true时。另外,我希望能够,给定一个特殊的“线程ID”(可以是字符串,顺便说一句,请求的“线程ID”将通过参数列表传递给此函数),以检查线程id是否正在运行。如果线程仍在运行,则我希望重置其计数器。否则…如果它被请求但未运行,则应创建它。这是毫无意义的:线程可能在您检查它的那一刻正在运行,但下一刻完成。我发现了通过重新设计我的应用程序,因此接受此作为最终答案。