Re: thread questions
"Lisa Pearlson" <no@spam.plz> wrote in message
news:eYgTh7bhJHA.5540@TK2MSFTNGP06.phx.gbl...
Guys,
I think I found a way to do this..
typedef struct _MYPARAMS {
TCHAR szSubject[MAX_PATH];
HANDLE hEvent;
} MYPARAMS, *LPMYPARANS;
DWORD WINAPI SearchProc(LPVOID lpParameter)
{
LPMYPARAMS p = (LPMYPARAMS) lpParameter;
while (WAIT_TIMEOUT == WaitForSingleObject(p->hNotify, 1000)) {
// do polling here
}
delete p;
return 0;
}
Why wait and waste 1 second here? You can use 0 for the timeout.
WaitForSingleObject will return WAIT_OBJECT_0 if the event is signaled.
HANDLE DoSearch(LPCTSTR lpszSubject)
{
LPMYPARAMS p = new MYPARAMS;
_tcsncpy(p->szSubject, lpszSubject, MAX_PATH);
p->hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
HANDLE hThread = CreateThread(NULL, 0, SearchProc, p, 0, NULL);
CloseHandle(hThread);
return p->hEvent;
}
If your thread function uses the runtime library then you are supposed to
use _beginthreadex instead of CreateThread. The library needs to know.
int _tmain(int argc, _TCHAR* argv[])
{
HANDLE hSearch1 = DoSearch(_T("Some subject"));
if (WAIT_OBJECT_0 == WaitForSingleObject(hSearch1, 3000)) {
// found result within 3 seconds
}
// even if function did not complete in 3 seconds, closing handle will
make WaitForSingleObject in thread terminate so thread can exit!
CloseHandle(hSearch1); // this will terminate the WaitForSingleObject
in the thread and make it terminate!
No, you should use SetEvent to signal WaitForSingleObject.
return 0;
}
So what is wrong with this code?
Normally you would do a WaitForSingleObject on thread handle, to wait for
it to complete before exitting the application. What happens if you
prematurely exit the application? Will thread have chance to complete or
will it be forcefully killed, causing potential memory leaks?
Lisa
If you don't assure that the thread has exited it might keep running even
when _tmain has returned. You should signal the thread to exit, then wait
until it does so before _tmain returns.
--
Scott McPhillips [VC++ MVP]