我有一个接受回调的函数,并用它来处理 10 个单独的线程。但是,通常情况下并非所有工作都需要。例如,如果在第三个线程上获得了所需的结果,它应该停止对剩余活动线程进行的所有工作。
这里的这个答案表明,除非你让回调函数接受一个额外的参数,否则这是不可能的,std::atomic_bool
这表明函数是否应该提前终止。
这个解决方案对我不起作用。工人在一个基类中旋转,这个基类的重点是抽象出多线程的细节。我怎样才能做到这一点?我预计我将不得不放弃std::async
更多涉及的事情。
#include <iostream>
#include <future>
#include <vector>
class ABC{
public:
std::vector<std::future<int> > m_results;
ABC() {};
~ABC(){};
virtual int callback(int a) = 0;
void doStuffWithCallBack();
};
void ABC::doStuffWithCallBack(){
// start working
for(int i = 0; i < 10; ++i)
m_results.push_back(std::async(&ABC::callback, this, i));
// analyze results and cancel all threads when you get the 1
for(int j = 0; j < 10; ++j){
double foo = m_results[j].get();
if ( foo == 1){
break; // but threads continue running
}
}
std::cout << m_results[9].get() << " <- this shouldn't have ever been computed\n";
}
class Derived : public ABC {
public:
Derived() : ABC() {};
~Derived() {};
int callback(int a){
std::cout << a << "!\n";
if (a == 3)
return 1;
else
return 0;
};
};
int main(int argc, char **argv)
{
Derived myObj;
myObj.doStuffWithCallBack();
return 0;
}