?
Solved

Terminating a thread

Posted on 2002-04-25
6
Medium Priority
?
257 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 86

Accepted Solution

by:
jkr earned 400 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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Often, when implementing a feature, you won't know how certain events should be handled at the point where they occur and you'd rather defer to the user of your function or class. For example, a XML parser will extract a tag from the source code, wh…
IntroductionThis article is the second in a three part article series on the Visual Studio 2008 Debugger.  It provides tips in setting and using breakpoints. If not familiar with this debugger, you can find a basic introduction in the EE article loc…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
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…
Suggested Courses

650 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