大佬教程收集整理的这篇文章主要介绍了c – 我可以在不等待未来限制的情况下使用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上)使用内部线程池.
谢谢.
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,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 :: launch :: async运行的任务必须像在新线程中一样运行,因此任何线程局部变量都不能从一个任务持久存在.但通常并不重要.
以上是大佬教程为你收集整理的c – 我可以在不等待未来限制的情况下使用std :: async吗?全部内容,希望文章能够帮你解决c – 我可以在不等待未来限制的情况下使用std :: async吗?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。