c++ - 我可以在不等待 future 限制的情况下使用 std::async 吗?

标签 c++ multithreading c++11 asynchronous stdasync

高级
我想在异步模式下调用一些没有返回值的函数,而无需等待它们完成。如果我使用 std::async future 对象在任务结束之前不会破坏,这会使调用在我的情况下不同步。

示例

void sendMail(const std::string& address, const std::string& message)
{
    //sending the e-mail which takes some time...
}

myResonseType processRequest(args...)
{
    //Do some processing and valuate the address and the message...

    //Sending the e-mail async
    auto f = std::async(std::launch::async, sendMail, address, message);

    //returning the response ASAP to the client
    return myResponseType;

} //<-- I'm stuck here until the async call finish to allow f to be destructed.
  // gaining no benefit from the async call.

我的问题是

  1. 有没有办法克服这个限制?
  2. 如果 (1) 不是,我是否应该实现一次线程来获取那些“僵尸” future 并等待它们?
  3. (1) 和(2) 都不是,有没有其他选择,然后只建立我自己的线程池?

注意:
我宁愿不使用线程+分离选项(由@galop1n 建议),因为创建一个新线程有我希望避免的开销。使用 std::async 时(至少在 MSVC 上)正在使用内部线程池。

谢谢。

最佳答案

您可以将 future 移动到全局对象中,因此当本地 future 的析构函数运行时,它不必等待异步线程完成。

std::vector<std::future<void>> pending_futures;

myResonseType processRequest(args...)
{
    //Do some processing and valuate the address and the message...

    //Sending the e-mail async
    auto f = std::async(std::launch::async, sendMail, address, message);

    // transfer the future's shared state to a longer-lived future
    pending_futures.push_back(std::move(f));

    //returning the response ASAP to the client
    return myResponseType;

}

注意如果异步线程引用 processRequest 函数中的任何局部变量,这是不安全的。

While using std::async (at least on MSVC) is using an inner thread pool.

这实际上是不符合标准的,标准明确规定使用 std::launch::async 运行的任务必须像在新线程中一样运行,因此任何线程局部变量都不得从一个任务交给另一个。不过这通常并不重要。

关于c++ - 我可以在不等待 future 限制的情况下使用 std::async 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21531096/

相关文章:

java - 与一个虚拟对象而不是这个同步

c++ - Uniform_real 不接受 numeric_limits::lowest()

Python.使用带有线程的队列

c++ - 使用信号量并调用 wait() 和 signal()

c++ - C++11 是否重新初始化已初始化的成员字段?

c++ - 在没有系统调用(管道)的线程之间使用 std::istream 和 std::ostream

c++ - 删除动态数组的一部分并增加其他部分

c++ - 模糊的 C++ 编译错误

c++ - SFML (C++) 中的正确碰撞

c++ - C++ 中的 Matlab griddata 等价物