Solved

Terminating a thread

Posted on 2002-04-25
6
255 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
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!

 
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: 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.

Question has a verified solution.

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

Introduction This article is a continuation of the C/C++ Visual Studio Express debugger series. Part 1 provided a quick start guide in using the debugger. Part 2 focused on additional topics in breakpoints. As your assignments become a little more …
Container Orchestration platforms empower organizations to scale their apps at an exceptional rate. This is the reason numerous innovation-driven companies are moving apps to an appropriated datacenter wide platform that empowers them to scale at a …
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
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.

707 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