std::future<T> 只能 get 一次,有些情况是需要多个线程都获取执行结果的,所以浅封装一下方便使用。目前不需要移动或拷贝,有需要了再添加相应的函数:
template<typename T>
class Future {
private:
std::mutex fur_mutex;
std::future<T> fur_res;
std::optional<T> opt_res;
public:
Future(std::future<T>&& fur) {
fur_res = std::move(fur);
}
/// @brief 试着获取结果。
/// @param res 结果。
/// @return true:有结果 false:没结果
bool try_get(T& res) {
std::scoped_lock<std::mutex> lck(fur_mutex);
std::cout << "try_get\n";
if (fur_res.valid()) {
res = fur_res.get();
opt_res = res;
return true;
}
else {
if (opt_res.has_value()) {
res = opt_res.value();
return true;
}
else {
return false;
}
}
}
};
使用方法:
void TestFurture() {
auto work_func = []() {
Sleep(1000);
return false;
};
Future<bool> f(std::async(work_func));
auto wait_func = [&]() {
bool res;
return f.try_get(res);
};
std::vector<std::future<bool>> furv;
for (int i = 0; i < 10; i++) {
auto res = std::async(wait_func);
furv.push_back(std::move(res));
}
Sleep(2000);
system("pause");
}