ron*_*nag 155
Future和Promise是异步操作的两个独立方面.
std::promise 由异步操作的"生产者/编写者"使用.
std::future 由异步操作的"使用者/读者"使用.
将它分成这两个独立的"接口"的原因是隐藏 "消费者/读者"的"写入/设置"功能.
auto promise = std::promise<std::string>();
auto producer = std::thread([&]
{
promise.set_value("Hello World");
});
auto future = promise.get_future();
auto consumer = std::thread([&]
{
std::cout << future.get();
});
producer.join();
consumer.join();
Run Code Online (Sandbox Code Playgroud)
使用std :: promise实现std :: async的一种(不完整的)方法可能是:
template<typename F>
auto async(F&& func) -> std::future<decltype(func())>
{
typedef decltype(func()) result_type;
auto promise = std::promise<result_type>();
auto future = promise.get_future();
std::thread(std::bind([=](std::promise<result_type>& promise)
{
try
{
promise.set_value(func()); // Note: Will not work with std::promise<void>. Needs some meta-template programming which is out of scope for this question.
}
catch(...)
{
promise.set_exception(std::current_exception());
}
}, std::move(promise))).detach();
return std::move(future);
}
Run Code Online (Sandbox Code Playgroud)
使用std::packaged_task哪个是帮手(即它基本上就是我们上面做的那样)std::promise你可以做以下更完整,可能更快的事情:
template<typename F>
auto async(F&& func) -> std::future<decltype(func())>
{
auto task = std::packaged_task<decltype(func())()>(std::forward<F>(func));
auto future = task.get_future();
std::thread(std::move(task)).detach();
return std::move(future);
}
Run Code Online (Sandbox Code Playgroud)
请注意,这与std::async在std::future破坏实际阻塞之前返回的内容略有不同,直到线程完成.