|
-
June 10th, 2017, 02:29 AM
#1
[RESOLVED] Why doesn't this method of closing a worker thread work?
I have an MFC application whose GUI has a start and a stop button. The start button calls a function which I want to run in the background, periodically. My solution was to use the SetTimer function to call the OnTimer function at regular intervals. This function then creates a thread using AfxBeginThread and then populates the structure that I pass to the thread as a parameter. All this works just fine.
What I would like to do now is the make the stop button end the thread. I have read about TerminateThread but it seems too risky. Since I want to close the worker thread from another thread, I know I can't use AfxEndThread, but I wanted to know why the following solution doesn't work.
What I have tried:
I created an int variable called count and set it to 0 whenever start is pressed, and set it to 1 whenever stop is pressed.
The structure I am passing into AfxBeginThread looks like this
Code:
typedef struct THREADSTRUCT
{
MyGUIDlg* _this;
int flag;
//you can add here other parameters you might be interested on
} THREADSTRUCT;
When start is pressed the SetTimer function is called, whose callback function is defined like this:
Code:
void MyGUIDlg::OnTimer(UINT_PTR nIDEvent)
{
THREADSTRUCT* _param = new THREADSTRUCT;
_param->_this=this;
_param->flag = count;
AfxBeginThread(StartThread, _param);
CDialog::OnTimer(nIDEvent);
}
In my StartThread function I have added the following:
Code:
UINT MyGUIDlg::StartThread(LPVOID param)
{
THREADSTRUCT *ts = (THREADSTRUCT*)param;
if((ts->flag)==1)
{
//Use AfxEndThread to close this thread
}
return 0;
}
But this doesn't seem to work, any thoughts why?
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|