Solved

Terminating a thread

Posted on 2002-04-25
6
249 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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

When writing generic code, using template meta-programming techniques, it is sometimes useful to know if a type is convertible to another type. A good example of when this might be is if you are writing diagnostic instrumentation for code to generat…
This article will show you some of the more useful Standard Template Library (STL) algorithms through the use of working examples.  You will learn about how these algorithms fit into the STL architecture, how they work with STL containers, and why t…
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

914 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

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now