C++如何等待多个线程中任意一个执行完毕并获取其返回值
实现方案
要实现等待任意线程完成且可识别具体是哪个线程完成,可采用轮询future就绪状态的方案,该方案兼容C++11及以上标准,无需引入额外依赖。
核心实现逻辑
循环遍历所有future,通过wait_for方法设置短超时检查每个future的就绪状态,一旦找到就绪的future,即可通过遍历下标确定对应线程,同时获取返回值后直接退出等待逻辑。
完整修改后代码
#include <iostream> #include <stdlib.h> #include <future> #include <vector> #include <chrono> #include <atomic> // 原子终止标记,用于通知其余线程提前退出 std::atomic<bool> stop_flag = false; int random_algorithm(){ // 注意:rand()不是线程安全的,生产环境建议替换为线程局部的<C++11 random>库实现 while(!stop_flag) { int random_number = rand() % 10 + 1; if (random_number > 5){ return random_number; } } return 0; } int main(){ std::vector<std::future<int>> thread_vec; for(int i=0;i<5;++i){ std::future<int> t = std::async(std::launch::async, random_algorithm); thread_vec.push_back(std::move(t)); } // 替换原有循环的等待逻辑 int completed_thread_idx = -1; int result = 0; while (completed_thread_idx == -1) { for (int i = 0; i < thread_vec.size(); ++i) { auto status = thread_vec[i].wait_for(std::chrono::milliseconds(1)); if (status == std::future_status::ready) { completed_thread_idx = i; result = thread_vec[i].get(); break; } } } // 通知剩余线程停止运行 stop_flag = true; std::cout << "第" << completed_thread_idx + 1 << "个线程完成,返回值:" << result << std::endl; // 后续主流程逻辑 return 0; }
关键说明
- 你需要额外引入
<chrono>头文件使用时间相关接口,引入<atomic>实现线程安全的终止标记。 - 代码中记录的
completed_thread_idx对应你启动线程时的顺序下标,从0开始,即可精准识别是哪一个线程完成执行。 - 如果不需要终止剩余线程,可以去掉
stop_flag相关逻辑,剩余线程会在后台执行到满足条件后自动退出。 - 若要降低轮询的CPU占用,可以将
wait_for的超时时间适当调大,例如设置为std::chrono::milliseconds(10)。
内容的提问来源于stack exchange,提问作者networkstudent
相关产品推荐
相关产品推荐

