如何正确使用hpx::when_any函数?代码报错问题求解
解决HPX when_any静态断言错误及实现任务替换逻辑
错误原因分析
你遇到的static assertion failed: result type must be constructible from input type错误,根源在于then回调的返回类型不匹配:
hpx::when_any(futures)返回的是hpx::future<hpx::when_any_result<std::vector<hpx::future<int>>>>- 你在
then的lambda中直接返回传入的future对象,导致f2的类型变为hpx::future<hpx::future<hpx::when_any_result<...>>> - 后续调用
f2.get()得到的是嵌套的future,而非预期的when_any_result,类型不匹配触发断言。
修正后的代码(实现任务替换逻辑)
以下代码实现了核心需求:维护N个并行任务,每当有一个任务完成时,立即替换为新任务,持续执行:
#include <iostream> #include <vector> #include <chrono> #include "hpx/hpx_main.hpp" #include "hpx/future.hpp" #include "hpx/thread.hpp" int dummy(int a) { // 模拟耗时任务,方便观察替换逻辑 hpx::this_thread::sleep_for(std::chrono::seconds(1)); std::cout << "任务完成: " << a << std::endl; return a; } int main() { const int parallel_count = 3; // 并行任务组数 std::vector<hpx::future<int>> futures; futures.reserve(parallel_count); // 初始化第一批任务 for (int i = 0; i < parallel_count; ++i) { futures.push_back(hpx::async(dummy, i)); } int task_id = parallel_count; // 新任务的起始ID for (int round = 0; round < 5; ++round) { // 模拟5轮任务替换,可按需调整 // 等待任意一个任务完成 auto result = hpx::when_any(futures).get(); // 获取完成任务的结果和索引 int completed_index = result.index; int completed_value = result.futures[completed_index].get(); std::cout << "已完成任务索引: " << completed_index << ", 结果: " << completed_value << std::endl; // 替换完成的任务为新任务 futures[completed_index] = hpx::async(dummy, task_id++); } // 等待剩余所有任务完成 hpx::wait_all(futures); return 0; }
关键修正点说明
- 移除不必要的
then回调:直接调用hpx::when_any(futures).get()获取when_any_result,避免嵌套future的类型问题 - 实现任务替换逻辑:
- 通过
result.index获取完成任务在vector中的位置 - 替换该位置的future为新的异步任务
- 循环执行直到达到预期的任务轮次
- 通过
- 增加
hpx::wait_all确保最后一批任务全部完成
内容的提问来源于stack exchange,提问作者superdelfin
相关产品推荐
相关产品推荐

