当我访问它时,这个异步技巧会起作用还是状态会悬空?

Ger*_*ago 13 c++ multithreading asynchronous c++11 dangling-pointer

我面临的情况是std::async完全异步启动操作会很好.

future<void> MyClass::MyAsyncFunc() {
    std::future<void> f = std::async(...);
    return f;
}  // The future goes out of scope, will block.
Run Code Online (Sandbox Code Playgroud)

问题是如果我不保存未来,该功能将在最后阻止.我希望这不会发生.

这将阻止在std::future函数范围的末尾调用它的析构函数:

shared_ptr<future<void>> MyClass::MyAsyncFunc() {
    auto shared_ftr = std::make_shared<std::future<void>>();
    *shared_ftr = std::async([shared_ftr]() {...});
    return shared_ftr;
}
Run Code Online (Sandbox Code Playgroud)

这可能有用吗?当我不将结果保存在变量中时会发生什么?

Nim*_*Nim 6

这是一个完全成熟的例子.这种模式确实有效,我在boost asio和异步操作中广泛使用它.

#include <chrono>
#include <iostream>
#include <future>
#include <memory>
#include <thread>

std::shared_ptr<std::future<int>> get_task()
// std::future<int> get_task() // rely on move, future supports move
{
  auto f = std::make_shared<std::future<int>>();
  //std::future<int> f = std::async(std::launch::async, [] {
  *f = std::async(std::launch::async, [f] {
    (void) f;
    std::cout << "calculating" << std::endl;
    for (int x = 0; x < 10; ++x)
      std::this_thread::sleep_for( std::chrono::milliseconds( 200 ) );
    std::cout << "done." << std::endl;
    return 100;
  });

  return f;
}


int main(void)
{
  std::cout << "getting task" << std::endl;
  //auto f = get_task(); <-- the future is moved not copied, so there is no block here
  get_task();
  std::cout << "waiting" << std::endl;
//  f.wait(); <-- now wait for it to complete...
//  std::cout << " got: " << f.get() << std::endl;
  // Wait for the truly async task to complete...
  std::this_thread::sleep_for(std::chrono::milliseconds(3000));
}
Run Code Online (Sandbox Code Playgroud)

我要表达的唯一问题是等到最后,没有捕获future(无论是移动还是通过shared_ptr),你无法在任务完成之前阻止应用程序终止...

如果你有其他方法可以确保延续,那么这种shared_ptr方法可以正常工作.另外,随着移动的未来,它更清洁......