I would like to implement branch and bound search in a multithreaded manner. In particular, I want to use async
to wrap the search calls at each branch, then just wait until some thread comes up with the answer, and just exit. (Ideally, I would want to cancel the other threads, but thread cancelling is not in the standard). Here is some simplified code :
#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()
is the search function. It returns true/false based on whether it found the answer or not. I return a random answer for illustration. But the crux of the problem is in the for loop that calls tasks[i].wait()
. Right now, I am waiting sequentially for tasks to finish. Instead I want to do something like this :
auto x = wait_for_any(tasks.begin(), tasks.end());
x.get();
// cancel other threads.
// Profit?
What is a good way to achieve this?