Solved

Terminating a thread

Posted on 2002-04-25
6
252 Views
Last Modified: 2010-04-02
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.

class MyObject
{
static void ThreadControllingFunction(…)
{
     // large and complex function
}
// Constructor
MyObject()
{
     …
     // Launch the thread
     AfxBeginThread(ThreadControllingFunction,…)
};
// Destructor
~MyObject()
{
     // If  the thread still runs, how do I stop it here,
//  before the object is deleted ???
}
}
0
Comment
Question by:olegsp
6 Comments
 
LVL 32

Expert Comment

by:jhance
ID: 6969505
The best thing to do is to signal the thread and have it exit, that way you are able to have the thread close and resources and clean up anything needing cleaned up.  After you signal it, you can just wait for it to terminate with WaitForSingleObject() or whatever.

There are many ways to signal a thread to do something.  Perhaps the simplest is to have a variable that can be set by the master process to signal that the thread is to exit.  Just have the thread check the flag at periodic intervals to see if it should go away.
0
 
LVL 86

Expert Comment

by:jkr
ID: 6969535
I'd follow jhance's recommendation. Usually, you would do this using an event:

long
WINAPI
ThreadProc ( LPVOID pv) {

HANDLE hTerm = (HANDLE) pv;
DWORD dwRes;
for ( ;;) {

  dwRes = WaitForSingleObject ( hTerm, 1);

  if ( WAIT_TIMEOUT != dwRes) {

  // Termination event was signaled, clean up & exit
  }
 }
}

If you have a "large and complex function
" rather than a loop, put checkpoints like this one periodically in your thread's code - narrow it down by placing these checkpoints before time-consuming operations.
0
 
LVL 1

Author Comment

by:olegsp
ID: 6969539
>Just have the thread check the flag at periodic intervals to see if it should go away.

That was my first idea, and it does not work well because of the complexity of the ThreadControllingFunction(). I really cannot put flags into all parts of this function - to me it would mean putting flags into almost every line of my project (how else can I tell at which point the object's destructor was executed ?). I guess, WaitForSingleObject() uses the same flag approach.
0
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

 
LVL 86

Accepted Solution

by:
jkr earned 100 total points
ID: 6969596
In this case, the only chance I see is 'TerminateThread()'.
0
 
LVL 4

Expert Comment

by:mblat
ID: 6969673
Just wondering: can't you setup an event that indicates that your thread is running or not?

taking from you orinail post and jrk suggestion and modified a little:

class MyObject
{
static void ThreadControllingFunction(…)
{
    MyObject::bThreadIsRunning == true;
    // large and complex function

   while(1)
   {
         dwRes = WaitForSingleObject ( hTerm, 1);

        if ( WAIT_TIMEOUT != dwRes) {

         // Termination event was signaled, clean up & exit
        SetEvent(hThreadIsOut);
        }
   }
   
}
// Constructor
MyObject()
{
    …
    // Launch the thread
    AfxBeginThread(ThreadControllingFunction,…)
};
// Destructor
~MyObject()
{
    // If  the thread still runs, how do I stop it here,
//  before the object is deleted ???
   WaitForSingleObject ( hThreadIsOut, INFINITE);

  // ok, INFINITE here may be bad idea - but smething realtevly long?
}
}


whould that work?
0
 
LVL 1

Author Comment

by:olegsp
ID: 6969911
Thank you for all your help, everyone.

All flagged methods are appropriate but they imply inserting the flags everywhere and then waiting for possibly long period of time. So I needed just what TerminateThread does.
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Unlike C#, C++ doesn't have native support for sealing classes (so they cannot be sub-classed). At the cost of a virtual base class pointer it is possible to implement a pseudo sealing mechanism The trick is to virtually inherit from a base class…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

839 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question