我想以多线程方式实现分支和边界搜索。特别是,我想使用async
在每个分支中包装搜索调用,然后等待某个线程出现答案,然后退出。 (理想情况下,我想取消其他线程,但线程取消不在标准中)。这里有一些简化代码:使用C++中的futures,异步和线程实现搜索11
#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()
是搜索功能。它根据是否找到答案返回true/false。为了说明,我返回一个随机答案。但问题的关键在于调用tasks[i].wait()
的for循环。现在,我正在顺序地等待任务完成。相反,我想要做这样的事情:
auto x = wait_for_any(tasks.begin(), tasks.end());
x.get();
// cancel other threads.
// Profit?
什么是实现这一目标的好方法?
顺便说一句,你在UB-土地已经来了由具有多线程调用'random_binary(RNG)',这是_not_线程安全的。 – ildjarn 2012-08-11 02:55:36