什么是C ++ 11的方式来触发异步任务并忘记它? [英] What's the C++ 11 way to fire off an asynchronous task and forget about it?
问题描述
我需要这样的东西:
void launch_task()
{
std::thread([](){ run_async_task(); });
}
除了线程的析构函数会终止我的任务。我不需要任何控制任务,也不需要一个返回值。它只需要运行它的过程,然后线程应该终止,并且C ++线程对象应该被丢弃。我需要什么C ++ 11设施?
Except thread's destructor will terminate my task. I don't need any control over the task, don't need a return value either. It just has to run its course and then the thread should terminate and C++ thread object should be disposed of. What C++ 11 facility do I need?
我看过 std :: async
找到我的case的用法的例子。它似乎是一个非常复杂的系统,我需要以某种方式存储和操纵 std :: future
或它会变成同步的(如果我的理解是正确的;我没有找到关于 std :: async
的好清楚的文章。
I've looked at std::async
, but couldn't find an example of usage for my case. It seems to be a pretty complicated system, and I'd need to somehow store and manipulate std::future
or it'd become synchronous (if my understanding is correct; I didn't find a good clear article on std::async
).
推荐答案
只要在创建后立即分离即可。
Just detach it immediately after creation.
std::thread([](){ run_async_task(); }).detach();
一旦分离,线程将不再是可连接的,所以〜thread )
将没有效果。
此回答讨论此行为的更多详细信息。
Once detached, the thread will no longer be joinable, so ~thread()
will have no effect.
This answer discusses more details of this behavior.
正如WB所提到的下面, std :: async
将无法工作,原因如下:引用。
As mentioned by W.B. below, std::async
will not work for the following reason, pulled from this reference.
如果从std :: async获取的std :: future有临时对象
生存期(不移动或绑定到变量),
std :: future的析构函数将在完整表达式的结尾处阻塞,直到
异步操作完成
If the std::future obtained from std::async has temporary object lifetime (not moved or bound to a variable), the destructor of the std::future will block at the end of the full expression until the asynchronous operation completes
这篇关于什么是C ++ 11的方式来触发异步任务并忘记它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!