简体   繁体   中英

std::thread that isn't a global variable but doesn't go out of scope when the end of the function that created it is reached?

So I ran across something that seems to defeat the purpose of std::thread or at least makes it less convenient.

Say I want to spawn an std::thread to perform a task one time and don't want to worry about it again after that. I create this thread near the end of a function so the std::thread will soon go out of scope, in my case, likely while the thread is still running. This creates a problem with a couple of solutions (or at least that I know of).

I can:

A) Make the std::thread a global variable so it doesn't go out of scope.

B) Call join() on the std::thread which defeats the purpose of spawning the thread.

Are there other, hopefully better, ways to handle this kind of situation?

What you want is std::thread::detach .

It decouples the actual thread of execution and the std::thread object, allowing you to destroy it without joining the threads.

You can use std::async .

async runs the function f asynchronously (potentially in a separate thread which may be part of a thread pool) and returns a std::future that will eventually hold the result of that function call.

Since you did not mention that you need to get the result of the thread, there is no need to get the future.

As pointed out in the comments, the destructor of std::future will block in any case, so you will have to move it to some global object (and manually manage deletion of unused futures), or you can move it into the local scope of the asynchronously called function.

Other preferred option is to allow the thread to consume tasks from a task-queue. For that, split the job into task chuncks and feed to the worker thread. To avoid polling, opt for condition_variable.

std::thread([&](){
                    while(running) // thread loop
                    { 
                       // consume tasks from queue
                    }
                 }).detach();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM