gpt4 book ai didi

c++ - 在 C++11 中使用 futures、async 和 thread 实现搜索

转载 作者:太空狗 更新时间:2023-10-29 19:42:08 25 4
gpt4 key购买 nike

我想以多线程方式实现分支定界搜索。特别是,我想使用 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() 的 for 循环。现在,我正在按顺序等待任务完成。相反,我想做这样的事情:

auto x = wait_for_any(tasks.begin(), tasks.end());
x.get();
// cancel other threads.
// Profit?

实现这一目标的好方法是什么?

最佳答案

std::future提供一个 valid() 使您可以检查结果是否可用而不会阻塞的功能,因此您可以只使用它,例如在忙等待循环中:

std::future<bool>* res_future = 0;
for(size_t i = 0; ; i==tasks.size()?i=0:++i){
// could add a timeout period to not completely busy-wait the CPU
if(tasks[i].wait_for(std::chrono::seconds(0)) == std::future_status::ready){
res = &tasks[i];
break;
}
}

bool res = res_future->get();

建议添加到 std::future ,为了使这样的任务更容易,是一个 .then(func_obj)异步调用 func_obj 的方法当结果可用时,您可以在其中设置标志或其他内容。

遗憾的是,我不知道有什么方法可以实现 wait_for_any以除上述以外的任何其他方式。 :/

template<class FwdIt>
std::future<bool> wait_for_any(FwdIt first, FwdIt last)
{
return std::async([=]{
for(FwdIt cur(first); ; cur==last?cur=first:++cur){
// could add a timeout period to not completely busy-wait the CPU
if(cur->wait_for(std::chrono::seconds(0)) == std::future_status::ready)
return cur->get();
});
}

线程销毁通常通过协作取消来完成。

P. S.: std::future<T>::get()会自动wait()如果结果不可用。

关于c++ - 在 C++11 中使用 futures、async 和 thread 实现搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11910051/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com