高水平
我想在异步模式下调用一些没有返回值的函数,而不等待它们完成。如果我使用 std::async ,则未来对象在任务结束之前不会破坏,这使得调用在我的情况下不同步。
Example
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)是否否,除了构建我自己的线程池之外还有其他选择吗?
note:
我宁愿不使用线程+分离的选项(由@galop1n建议),因为创建新线程会产生我希望避免的开销。当使用 std::async (至少在 MSVC 上)时,正在使用内部线程池。
Thanks.
您可以将 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
功能。
使用时std::async
(至少在 MSVC 上)正在使用内部线程池。
这实际上是不符合标准的,标准明确表示任务运行std::launch::async
必须像在新线程中一样运行,因此任何线程局部变量都不能从一个任务持续到另一个任务。但这通常并不重要。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)