有没有办法将std::async与std::experimental::future一起使用?
Is there a way to use std::async with std::experimental::future?
注意:即使在 C++17 中,下面也是非法的!
#include <thread>
#include <future>
#include <experimental/future>
using namespace std;
int step1(experimental::future<int>)
{
return {};
}
int step2(experimental::future<int>)
{
return {};
}
int step3(experimental::future<int>)
{
return {};
}
int main()
{
return async([](){ return {}; })
.then(step1)
.then(step2)
.then(step3)
.get();
}
C++1Z提供两种类型的future
:
std::future
std:experimental::future
但是,std::async
只返回std::future
,因此上面的代码是非法的。如果std::async
返回std:experimental::future
,那就没问题了。
我的问题是:
有没有办法将std::async
与std::experimental::future
一起使用,使上面的代码在 C++1z 下合法?
有
没有办法将
std::async
与std::experimental::future
一起使用,使上面的代码在 C++1z 下合法?
不。std::async
返回一个std::future<T>
尽管名称如此,但它与std::experimental::future<T>
完全无关。
您必须编写自己的async
版本,为您提供新的future
。简化版本如下:
template <class F, class... Args,
class R = std::invoke_result_t<std::decay_t<F>, std::decay_t<Args>...>>
std::experimental::future<R> new_async(F&& f, Args&&... args)
{
std::experimental::promise<R> p;
auto fut = p.get_future();
std::thread thread([p=std::move(p), f=std::forward<F>(f),
args=std::tuple<std::decay_t<Args>...>(std::forward<Args>(args)...)] () mutable
{
try
{
if constexpr(std::is_void_v<R>)
{
std::apply(std::move(f), std::move(args));
p.set_value();
}
else
{
p.set_value(std::apply(std::move(f), std::move(args)));
}
}
catch(...)
{
p.set_exception(std::current_exception());
}
});
thread.detach();
return fut;
}
这不像async
那样支持其他启动策略,但这只是一个开始。
看起来std::experimental::future
具有与std::future
相同的构造函数,因此应该可以从std::future
构造std::experimental::future
。但是,正如ildjarn所指出的那样,它实际上不是根据最新草案,因此在TS相应更改之前似乎没有办法做到这一点。
相关文章:
- 架构决策:返回std::future还是提供回调
- std::p romise::set_value() 和 std::future::wait() 是否提供内存围栏?
- 修改在 std::future 的 lambda 中引用捕获的值
- C++ std::future没有被调用
- 对于等待以 std::future wait() 返回的函数的 CPU 使用率或检查标志在循环中休眠一段时间哪个更好?
- Make zmqpp::socket::connect a std::future
- std::future可以比std::promise活得更长吗
- std::future::get()或std::future::wait()是std::thread::join()的替
- 当 std::future 准备好被检索时发出信号主线程
- 当多次调用时,"std::future::then"的行为是什么?
- 使用 std::future 的不完整类型无效使用
- 为什么 std::future::wait_for 的行为不符合预期?
- 是什么给了 std::future 一些共享状态
- STD :: Future no_state异常与断言
- 标准是否保证在移动std::p ackaged_task后安全使用std::future?
- 将 Boost 链与 std::future 结合使用
- 删除 std::future 和 std::p romise 的空白专用化
- std::future给了我错误3,我做错了什么
- 如何在 std::future 的向量中调用异步函数
- 在 std::future::unwrap() 和 std::future::get() 中竞争