我想以多线程方式实现分支和绑定搜索。特别是,我想用它async
来包装每个分支的搜索调用,然后等到某个线程给出答案,然后退出。(理想情况下,我想取消其他线程,但线程取消不在标准中)。这是一些简化的代码:
#include <iostream>
#include <random>
#include <future>
#include <thread>
using namespace std;
mt19937 rng;
uniform_int_distribution<unsigned> random_binary(0, 1);
bool search() {
return static_cast<bool>(random_binary(rng));
}
#define N 10000
int main()
{
rng.seed(42);
std::vector<future<bool>> tasks;
for (unsigned i=0; i<N; ++i)
tasks.push_back(async(launch::async, search));
// Don't want to wait sequentially here.
for (unsigned i=0; i<N; ++i) {
tasks[i].wait();
if (tasks[i].get()) {
cout << "i = " << i << "\n";
break;
}
}
return 0;
}
search()
是搜索功能。它根据是否找到答案返回真/假。我返回一个随机答案以供说明。但问题的症结在于调用tasks[i].wait()
. 现在,我正在按顺序等待任务完成。相反,我想做这样的事情:
auto x = wait_for_any(tasks.begin(), tasks.end());
x.get();
// cancel other threads.
// Profit?
什么是实现这一目标的好方法?