我想以多線程方式實現分支和邊界搜索。特別是,我想使用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