带有asycron的c++boost thread_group返回
c++ boost thread_group with asycron returns
我正在尝试编写一个函数,该函数同时处理线程组中线程的输入参数和返回值。
我的示例类:
// 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);
}
}
我想遍历线程,并能够检查DoWork是否返回true。
我该如何实现?
首先,使用thread_group
,您不能迭代线程对象。因此,如果这是您想要的,请考虑将线程对象存储在其他容器中。
此外,您不能便携地等到一个线程完成,但如果您不介意使用特定于Windows的API,则可以使用WaitForMultipleObjects
来完成此操作。
但是,我建议您重新设计您的应用程序,以避免此类技巧。
相关文章:
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- 什么时候在C++中返回常量引用是个好主意
- 你能重载对象变量名本身返回的内容吗
- 为什么 Serial.println(<char[]>);返回随机字符?
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 如何获取std::result_of函数的返回类型
- QueryWorkingSet总是返回false
- (C++)分析树以计算返回错误值的简单算术表达式
- 访问者访问变体并返回不同类型时出错
- 如何返回一个类的两个对象相加的结果
- OpenInventor从9.8升级到10.4.2后,GLSL纹理返回零
- lower_bound()返回最后一个元素
- "throw expression code" 1e7 >返回 d 是什么?投掷标准::overflow_error( "too big" ) : d;意味 着?
- 奇怪的(对我来说)返回声明 - 在谷歌上找不到任何关于它的信息
- 如何取消对nullptr的屏蔽,返回正确的对象
- 奇怪的结构&GCC&clang(void*返回类型)
- 架构决策:返回std::future还是提供回调
- 从python中调用C++函数并获取返回值
- 矩阵向量乘法(cublasDgemv)返回零
- 为什么模板类中的对象不能返回值