【发布时间】:2014-02-27 03:49:57
【问题描述】:
高级
我想在异步模式下调用一些没有返回值的函数,而无需等待它们完成。如果我使用 std::async 未来对象在任务结束之前不会破坏,这会使调用在我的情况下不同步。
示例
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) 为否,我是否应该执行一次线程来获取那些“僵尸”期货并等待它们?
- (1) 和 (2) 都没有,除了自己构建线程池还有其他选择吗?
注意:
我宁愿不使用线程+分离选项(由@galop1n 建议),因为创建一个新线程有我希望避免的开销。使用 std::async 时(至少在 MSVC 上)正在使用内部线程池。
谢谢。
【问题讨论】:
-
你 cannot do that with async 设计的。
-
我知道我做不到。我要问的是是否有人有一种简单的方法来扩展基本的 std::async 来做到这一点。如果不是,我应该采取什么方法来实现这一目标。 (可能根本不使用 std::async)。
-
嗯,这回答了你的标题问题:) 如果你想要线程池,也许你可以明确地做到这一点,而不是依赖于实现细节。
-
如果您需要发送多封电子邮件,请考虑使用异步代理库(VS 附带的 PPL 的一部分)。 msdn.microsoft.com/en-us/library/dd492627.aspx
-
只需
fork为sendMail的另一个进程,然后忘记它。 :)
标签: c++ multithreading c++11 asynchronous stdasync