Solved

Terminating A Thread Externally

Posted on 2006-07-24
8
415 Views
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?
0
Comment
Question by:reidy_boy
  • 3
  • 2
  • 2
  • +1
8 Comments
 
LVL 22

Accepted Solution

by:
mahesh1402 earned 125 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  )

-MAHESH
0
 
LVL 7

Expert Comment

by:nafis_devlpr
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
//function
{
................................
}

AfxEndThread(exitCode);

hope this helps

Nafis
0
 
LVL 1

Author Comment

by:reidy_boy
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.
0
ScreenConnect 6.0 Free Trial

Check out the updates in one game-changing release, ScreenConnect 6.0, based on partner feedback. New features include a redesigned UI that improves session organization and overall user experience. See the enhancements for yourself!

 
LVL 7

Expert Comment

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

Nafis
0
 
LVL 1

Author Comment

by:reidy_boy
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;
CDialog::OnClose();

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

Assisted Solution

by:AndyAinscow
AndyAinscow earned 75 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).
0
 
LVL 1

Author Comment

by:reidy_boy
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?
0
 
LVL 44

Expert Comment

by:AndyAinscow
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.)


ps.
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.
0

Featured Post

Is Your AD Toolbox Looking More Like a Toybox?

Managing Active Directory can get complicated.  Often, the native tools for managing AD are just not up to the task.  The largest Active Directory installations in the world have relied on one tool to manage their day-to-day administration tasks: Hyena. Start your trial today.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
xyBalance chalenge 58 93
ODBC Connection Logging, ADO.NET 6 64
dog bark java program 15 95
firstChar challenge 13 115
Introduction: Displaying information on the statusbar.   Continuing from the third article about sudoku.   Open the project in visual studio. Status bar – let’s display the timestamp there.  We need to get the timestamp from the document s…
Introduction: Hints for the grid button.  Nested classes, templated collections.  Squash that darned bug! Continuing from the sixth article about sudoku.   Open the project in visual studio. First we will finish with the SUD_SETVALUE messa…
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.
Microsoft Active Directory, the widely used IT infrastructure, is known for its high risk of credential theft. The best way to test your Active Directory’s vulnerabilities to pass-the-ticket, pass-the-hash, privilege escalation, and malware attacks …

777 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