Reputation: 1719
I have the following class that has a std::thread as one of its member fields:
class MyClass {
private:
std::thread auxThread;
void run();
public:
~MyClass();
void start();
}
MyClass:~MyClass() {
if (auxThread.joinable())
auxThread.join();
}
void MyClass::run() {
//do stuff
}
void MyClass::start() {
auxThread = std::thread (&MyClass::run, this); //Move assignment
}
I can start the auxThread on-demand thanks to initializing it with an empty constructor and later move-assigning it to a std::thread object associated with an actual thread of execution (via the start() function), but to minimize system resource usage I'd like to join() auxThread with the main thread immediately after run() has exited i.e. when auxThread's work is done instead of in the MyClass destructor. It looks like condition_variable could be used to wake a sleeping main thread and accomplish this, but I don't want to block the main thread except (hopefully) briefly with join().
Two questions:
Is having a thread whose execution function has exited a drain on resources if it is never joined with the main thread, or is the thread and all associated resources released when the execution function exits (such that join() would presumably be unnecessary and return immediately)?
Is it possible to call join() on auxThread from the main thread in response to run() exiting without blocking the main thread?
Upvotes: 3
Views: 1280
Reputation: 49008
Is having a thread whose execution function has exited a drain on resources if it is never joined with the main thread
Maybe. It depends on your implementation, but typically not.
is the thread and all associated resources released when the execution function exits
Probably, and if not, then as soon as possible by the OS. This is also implementation defined.
Is it possible to call join() on auxThread from the main thread in response to run() exiting without blocking the main thread?
Yes, but it wouldn't make any sense. The only thing that join
does is block until the function being executed is done. Calling join
again after run
finished executing is unnecessary and basically a no-op.
Also, the "resources" from the thread are minimal. I wouldn't expect that a lot of memory would be allocated just for a single thread like yours. RAM is pretty cheap nowadays, so you shouldn't worry about that, as you are not executing 5M threads in parallel, which would make no sense on a conventional computer anyways.
Upvotes: 3