0
why threa destructor calls terminate
Hi We know that C++ thread need to be joined or detached before main thread terminates. Non joined and non detached thread destructor calls terminate. Why so? Just wanted to understand the need of C++ implementation to call terminate ?
7 ответов
+ 3
It's just a cleanup measure to free up system resources, just like deallocating any heap space that the process left allocated upon termination. It is presumed unintentional if threads are left unjoined upon termination.
You can make it intentional and leave the thread running by detaching the thread before main terminates.
+ 3
It's been awhile since I studied this, so I got a refresher from ChatGPT. While the OS tracks processes in a Process Control Block (PCB), it tracks threads in a Thread Control Block (TCB) where they are like lightweight processes with less overhead. Both PCB and TCB are in system memory storage.
A join blocks the calling process (e.g., main) to wait for the thread to terminate. The return status/value is held in the TCB until the value can be assigned in main (or other caller). After termination and return value assignment the OS does a cleanup to remove the thread from the TCB - deallocate memory, clear the local stack, etc. There is less cleanup than a fully-independent process.
+ 2
I consider the Thread class to be a wrapper to system API calls. Destroying the Thread object does not necessarily kill the thread process. That leads to undefined behavior. You should either rejoin or detach the thread.
+ 1
A big part of programming is cleaning up behind yourself. If you allocate memory for something that you don't need anymore, you should release that memory when done. If you don't clean up after yourself, the program takes up more and more memory over time. That will cause problems.
Each language has it's own method to help clean up behind bad programming. Some better than others. The goal is the same. If you, as a programmer, don't clean up behind yourself then language features are designed to try and clean up behind you.
If you spawn a process, make sure you terminate it. If you allocate data, make sure you free/delete it.
0
What terminate ensures ? Nothing right?
Thread is Class and object has been created. That object go out of scope to trigger the destructor call.
Now, destructor of class object is called , what else cleaning is required 🙄? This is the point I am missing to underhand.
0
Sounds good. Just curious to know what it does when we join ? Does it do some cleaning from process control board or somewhere else ?
Thanks for sharing on this.
0
Thanks Brian