thread question

I have a timer that fires off every tenth of a second in my MainFrame class. The timer function creates a thread if there isn't already a thread created.

In my view class, if the user clicks a button, I kill the timer. However, when I kill the timer, my thread doesn't seem to run to completion, which causes problems.

doesn anyone know how I synchornize this so that after the user clicks the button, the thread finishes exiting normally, and the timer stops...

Thanks
[508 byte] By [mps2] at [2007-11-18 3:48:50]
# 1 Re: thread question
(1) Add a member variable to your main frame class that represents the thread state (running/stopped)

(2) When starting your thread, set that variable to running. When you want your thread to be terminated, set it to stopped.

(3) Pass a pointer to your main frame class. In your thread function use that pointer to check if your thread should terminate.

(4) If youre using a CWinThread derived class replace the following line in the Run() method

return CWinThread::Run();

with

return 0; (or whatever you want to return)

Make sure the m_bAutoDelete flag is set to the appropriate value.

Hope this helps
Guido
Guido Niewerth at 2007-11-11 3:39:36 >
# 2 Re: thread question
To stop worker thread correctly, you need to set event. Thread
function should check this event periodically and when it is
signaled, exit.

In thread function:

while ( ... )
{
// do something

if ( WaitForSingleObject(hStopThread, 0) == WAIT_OBJECT_0 )
break;
}

To stop such thread set event and wait for thread finish:

SetEvent(hStopThread);
WaitForSingleObject(hThread, INFINITE); // wait when thread finished

Event is created using function CreateEvent.
Alex F at 2007-11-11 3:40:35 >
# 3 Re: thread question
Thanks Alex, that worked great.
mps2 at 2007-11-11 3:41:45 >