mercredi 5 septembre 2018

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?

Aucun commentaire:

Enregistrer un commentaire