Terminating a thread
Posted on 2002-04-25
My object creates a thread to do some background processing. The thread is created with AfxBeginThread soon after the object is initialized (for instance, in the object's constructor), and should exist as long as the object exists.
The problem is that the thread runs a large time-consuming function, and, when the object’s destructor is called to delete the object, the thread still may be running. In this case, the object gets destructed, all object data used by the thread becomes invalid, which causes exceptions in the still running thread.
As I mentioned, the large size of the thread-controlling function makes it impractical to insert in this function any checks for the present object validity, or any sync checks. In other words, any means of stopping the thread from inside the thread are difficult ro implement (maybe I am wrong ?).
Can I somehow kill my thread from the object’s destructor.
static void ThreadControllingFunction(…)
// large and complex function
// Launch the thread
// If the thread still runs, how do I stop it here,
// before the object is deleted ???