Re: WaitForSingleObject sleeps forewer
- From: Tim Roberts <timr@xxxxxxxxx>
- Date: Sat, 10 Mar 2007 15:19:51 -0800
agentd <agentd@xxxxxxxxxxxxxxxx> wrote:
Hi thanks for the information but still no solution
I see it! I see it! Is there a prize?
inline uintmsd_t Thread::_ThreadExecute(void* Ptr)
{
if(NULL==Ptr)
{
assert(NULL==Ptr);
return 1L;
}
reinterpret_cast<Thread*>(Ptr)->Execute();
return 0L;
}
This is not related to your problem, but are you aware that this "assert"
will never fire? I suspect you wanted to have the "assert" BEFORE the
"if".
inline bool Thread::Start()
{
if(NULL==m_ThreadHandle)
{
m_ThreadHandle=reinterpret_cast<HANDLE>(_beginthreadex(NULL,0,Thread::_ThreadExecute,this,0,NULL));
BOOL r =
::SetThreadPriority((HANDLE)m_ThreadHandle,THREAD_PRIORITY_LOWEST);
return true;
}
return false;
}
OK, so here we create the thread and tuck the handle away.
inline bool Thread::WaitForFinish()
{
if(NULL!=m_ThreadHandle)
{
DWORD retVal=::WaitForSingleObject((this->m_ThreadHandle),INFINITE);
And here is the wait that waits forever.
inline bool Thread::Stop()
{
if(NULL!=m_ThreadHandle)
{
if(0<TerminateThread(m_ThreadHandle,0))
{
CloseHandle(m_ThreadHandle);
m_ThreadHandle=NULL;
return true;
}
return false;
}
return true;
}
And here is the reason WHY it waits forever. You terminate the thread, and
then immediately close the handle. As soon as you close the handle, the
handle is invalid, so the WaitForSingleObject is looking at trash memory.
It will never fire.
You should either move the "CloseHandle" and "m_ThreadHandle=NULL" calls to
after the WaitForSingleObject, or put them in the destructor for the class.
When you are doing multithreaded programming, you ALWAYS have to think
about what order things are going to happen.
There is another issue here, however. Using TerminateThread is almost
always a bad idea. It should be considered an "emergency stop", because
the thread does not get a chance to clean itself up properly. A much
better design is to have a flag or an event that you set in the "Stop"
handler, which the thread code will monitor. When the flag or event is
set, the thread exits cleanly, and everybody is happy.
--
Tim Roberts, timr@xxxxxxxxx
Providenza & Boekelheide, Inc.
.
- References:
- Re: WaitForSingleObject sleeps forewer
- From: adebaene
- Re: WaitForSingleObject sleeps forewer
- From: Anton Bassov
- Re: WaitForSingleObject sleeps forewer
- From: agentd
- Re: WaitForSingleObject sleeps forewer
- Prev by Date: Shared memory and IOCP
- Next by Date: Re: Shared memory and IOCP
- Previous by thread: Re: WaitForSingleObject sleeps forewer
- Next by thread: Re: WaitForSingleObject sleeps forewer
- Index(es):
Relevant Pages
|