Terminating A Thread Externally

Posted on 2006-07-24
Medium Priority
Last Modified: 2013-11-20
I have an MFC dialog app that shows live updates on information coming into a database.  It does this by invoking a thread from OnInitDialog using AfxBeginThread.  This thread then goes round in a continuous loop, reading the database info and then outputting it to the screen.  The problem I am having is how to close this thread in a controlled way when my main application stops running.  I need the chance to return my dynamic memory to avoid debug assertion fail messages on shutdown, and ensure that when I write my data to the screen it will not cause my app to crash because the main dialog has been wrapped up.  AfxEndThread can only be called from inside the thread, there a way of terminating the thread from the main dialog app?
Question by:reidy_boy
  • 3
  • 2
  • 2
  • +1
LVL 22

Accepted Solution

mahesh1402 earned 500 total points
ID: 17166647
You need to arrange to signal to the thread, and then have the thread exit itself - safely. One way of doing this is to create an event and have the thread periodically check this event.  If the threads are using WaitForMultipleObject calls pass them an event that you set to tell them to shutdown. WaitForMultipleObject will return and its return code can cause the thread code to exit.

Refer : Using Worker Threads by  Joseph M Newcomer  : http://www.codeproject.com/threads/usingworkerthreads.asp ( ref : Pausing a Thread and Thread Shutdown  )


Expert Comment

ID: 17174128
just use a Global variable in the while loop condition to wether stop or go on with the threads.
like this

//Global Variable
int stopThread=0;//thread count starts from 1

in the thread functions parameter pass the thread number, this is because if you have multiple threads running at the same time then you have to signal the right Thread to stop. So when you need to stop the thread, in the main function do this:

//in main function
stopThread=2;//terminates the 2nd thread

//in the thread
//the while condition
while(stopThread != thisThread)//thisThread is the id of this threads passed from main through AfxBeginThread


hope this helps


Author Comment

ID: 17174738
I am now using WaitForSingleObject.  This works fine but with one problem.  Whenever I signal that I want my thread to end, the thread will continue running as it should until it reaches a line that is associated with the View class.  Two such lines are GetCurSel() and ResetContent().  When it tries to execute these lines the program freezes.
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!


Expert Comment

ID: 17175045
the program is freezing because you are exiting from the main function before the thread ends. You have to wait until the thread ends then exit from the main function. you can do this using a static thread count. whenever a thread ends before it ends it should decrease the thread count, so when the thread count becomes zero the main will exit.


Author Comment

ID: 17175373
I don't see how I can be exiting from the main function first.  The setup is this.  I have a boolean variable declared in my Dlg header file called KillThread.  In the dialog constructor I set this to 0.  I have a Close button on my main dialog window, and an OnClose method which is called when this button is pressed.  The code in this function reads as follows:

KillThread = 1;
myWorkerThread->m_bAutoDelete = FALSE;
WaitForSingleObject(myWorkerThread->m_hThread, INFINITE);
delete myWorkerThread;

So it is only after WaitForSingleObject has been executed (i.e. once my thread has been successfully ended) that it destroys the main window.
LVL 45

Assisted Solution

AndyAinscow earned 300 total points
ID: 17176150
<Whenever I signal that I want my thread to end, the thread will continue running as it should until it reaches a line that is associated with the View class.>

You are aware that MFC is not thread safe I hope.  (Calling an MFC window directly from another thread is a nono).

Author Comment

ID: 17176590
> You are aware that MFC is not thread safe I hope.
Er... no :-)

>Calling an MFC window directly from another thread is a >nono

What would be your approach to this task?  Would it be better for the thread to post a windows message that the View frame would then listen out for?
LVL 45

Expert Comment

ID: 17176695
<Would it be better for the thread to post a windows message that the View frame would then listen out for?>

Yes, you should use a technique such as that.   (From another thread you can call some MFC window functions directly, other will crash because it wants some thread specific info.)

Did you consider a simple 'DoEvents' function - it can make things appear multi-threaded even if they aren't.  What you have described sounds suspiciously like a case for that.

Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

Question has a verified solution.

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

Introduction: Finishing the grid – keyboard support for arrow keys to manoeuvre, entering the numbers.  The PreTranslateMessage function is to be used to intercept and respond to keyboard events. Continuing from the fourth article about sudoku. …
Introduction: Dialogs (2) modeless dialog and a worker thread.  Handling data shared between threads.  Recursive functions. Continuing from the tenth article about sudoku.   Last article we worked with a modal dialog to help maintain informat…
This Micro Tutorial will teach you how to add a cinematic look to any film or video out there. There are very few simple steps that you will follow to do so. This will be demonstrated using Adobe Premiere Pro CS6.
This video will show you how to get GIT to work in Eclipse.   It will walk you through how to install the EGit plugin in eclipse and how to checkout an existing repository.
Suggested Courses
Course of the Month16 days, 16 hours left to enroll

862 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