I have a program that does some background processing, in a separate thread. At the moment, I create it with:
terminate_thread = false;
threadhandle = std::make_shared<std::thread>([this]{MyProg::backgroundThread();});
before I terminate my program, I tell the thread to finish what they are doing, and join with it:
terminate_thread = true;
threadhandle->join();
My background thread isn’t quick enough (it’s doing network stuff), I’d like to change it to have a variable number of threads, so I am changing it to use an std::vector.
During the runtime of my program (which might be weeks), it might collect a lot of background threads (if the load varies).
How can I tell which threads are finished? Do I need to join them, or can I just remove them from my list?
I am open to some method other than a std::vector of threads, so long as I can increase and decrease the number of threads dynamically. All the threads use the same function. No information needs to be transferred between background threads and the main program (or vice versa), or between threads (since I’m processing files, the files are locked).
I’m pretty new to C++ and threads.
I am writing/compiling/running this on Linux.
I tried threadhandle.use_count() and threadhandle.unique() threadhandle.joinable(), which always return 1, true, and true, even after the thread has terminated.
If I call threadhandle.join()
, my main thread is blocked.
If I call detach(), I can’t join() when I’m ready to terminate. The threads could potentially take a while (up to 30 seconds) to end, I definitely want them to have the chance to finish.
If I just collect them all up, I might have a very long list by the end (I am more used to fork(), which leaves Zombie processes if you don’t clean them up).
I’ve searched Google, and stackoverflow. There are useful examples in Java and C#, but not C++
I could not find any way in the docs for std::thread – std::thread does not appear to have a “state” (or a way of getting the state).
I understand I could pass one variable to each thread, to let them say when they are done; this seems like a lot of overhead, for something that I would expect to be built in. It also wouldn’t handle if a thread exits unexpectedly, e.g. an exception.
Jay Bee is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.