Solved

Terminating a thread

Posted on 2002-04-25
6
248 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
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

  Included as part of the C++ Standard Template Library (STL) is a collection of generic containers. Each of these containers serves a different purpose and has different pros and cons. It is often difficult to decide which container to use and …
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 be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

747 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

11 Experts available now in Live!

Get 1:1 Help Now