Re: worker thread
On 5 Nov., 12:21, mfc <mfcp...@googlemail.com> wrote:
Ohh I like this answer :-)...
I tought so ;-)
Unfortunately, I don`t want to start the
worker thread in the document or view class.
I`ve my own class, called MyParamClass which is no subclass. This
class and the subclasses contains all information, which are needed
for the verificiation of the data. The verification will be done in
the worker thread.
So if the worker thread is only for the purpose of
verifying the data I would make all the variables
needed to control the worker thread memebers of
that class. That makes sence.
class MyParamClass
{
void StartMyWorkerThread();
protected:
CWinThread* m_pWorkerThread;
HANDLE m_hStopWorkerThread;
};
MyParamClass::MyParamClass()
{
m_pWorkerThread = NULL;
m_hStopWorkerThread = CreateEvent(NULL, TRUE, FALSE, NULL); // manual
reset, initially not set
}
void MyParamClass::StartMyWorkerThread()
{
// reset an old dead thread
if (m_pWorkerThread != NULL)
{
DWORD dwExitCode;
GetExitCodeThread(m_pWorkerThread->m_hThread, &dwExitCode);
if (dwExitCode == STILL_ACTIVE)
return; // worker thread already exists and is alive, do not start
it again
else
m_pWorkerThread = NULL;
}
// give the m_hStopWorkerThread handle to the worker thread
something->hStopWorkerThread = m_hStopWorkerThread;
m_pWorkerThread = AfxBeginThread(myThreadProc, something); //and
so on
}
void MyParamClass::ShutDownWorkerThreadSafely()
{
DWORD dwExitCode;
HANDLE hThread = m_pWorkerThread ? m_pWorkerThread->m_hThread : NULL;
if (m_pWorkerThread != NULL &&
GetExitCodeThread(hThread, &dwExitCode) &&
dwExitCode == STILL_ACTIVE)
{
// Stop the worker thread by setting the event.
SetEvent(m_hStopWorkerThread);
// Wait for thread to end itself
while (GetExitCodeThread(hThread, &dwExitCode) &&
dwExitCode == STILL_ACTIVE)
{
WaitForSingleObject(hThread, 1);
}
m_pWorkerThread = NULL;
}
}
void MyParamClass::~MyParamClass()
{
ShutDownWorkerThreadSafely();
::CloseHandle(m_hStopWorkerThread);
}
UINT myThreadProc(LPVOID pParam)
{
YourStruct* yourS = (YourStruct*)pParam;
HANDLE hStopWorkerThread = yourS->hStopWorkerThread;
while (true)
{
//Do something importnt
//check hStopWorkerThread
if (WaitForSingleObject(pDoc->hStopWorkerThread, 0)
== WAIT_OBJECT_0)
break; // Terminate this thread by existing the proc.
}
}
I`ve only installed one global variable installed for this
MyParamClass. In the thread I only do the verification, which means I
didn`t change any variable. After performing the verification and
everything was successfull, I will send a PostMessage back to the
mainthread to do all required changes.
So from you global variables you can call StartMyWorkerThread
resp. ShutDownWorkerThreadSafely (if you wish to).
HTH