Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
786 views
in Technique[技术] by (71.8m points)

multithreading - What's the C++ 11 way to fire off an asynchronous task and forget about it?

I need something like this:

void launch_task()
{
    std::thread([](){ run_async_task(); });
}

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?

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).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Just detach it immediately after creation.

std::thread([](){ run_async_task(); }).detach();

Once detached, the thread will no longer be joinable, so ~thread() will have no effect. This answer discusses more details of this behavior.

As mentioned by W.B. below, std::async will not work for the following reason, pulled from this reference.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...