Re: WaitForSingleObject freezes application
From: Tobias Güntner (fatbull_at_web.de)
Date: 07/18/04
- Next message: Joseph M. Newcomer: "Re: Menu items become unexpectedly disabled"
- Previous message: Macca: "Automatic Start up of my application"
- In reply to: Mike Gleason Jr Couturier: "WaitForSingleObject freezes application"
- Messages sorted by: [ date ] [ thread ]
Date: Sun, 18 Jul 2004 20:14:46 +0200
Mike Gleason Jr Couturier wrote:
>
> m_pThread = AfxBeginThread(DoDownload, this);
>
[snip]
> Finally here is my abort button actions :
>
> [...]
> csl.Lock();
> m_bAbort = TRUE;
> csl.Unlock();
> TRACE("Waiting for thread\n");
> WaitForSingleObject(m_pThread->m_hThread, INFINITE);
> TRACE("Thread returned !\n");
>
> [...]
>
There's yet another bug in your code. When you create threads using
AfxBeginThread and a worker function, the returned thread will be
deleted as soon as the thread ends. In the worst case the thread
terminates (and destroys *m_pThread) just between m_bAbort=TRUE and the
call of WFSO.
UINT AFX_CDECL Thread(LPVOID)
{
Sleep(100);
return 0;
}
CWinThread* pThread = AfxBeginThread(Thread, 0);
Sleep(1000); // Maybe the scheduler decided to do a task switch here.
// If Thread() finishes, *pThread becomes invalid!
WaitForSingleObject(pThread->m_hThread, INFINITE); // Invalid handle!
You should prevent MFC from automatically deleting the thread:
m_pThread = AfxBeginThread(DoDownload, this,
THREAD_PRIORITY_NORMAL, 0, CREATE_SUSPENDED);
m_pThread->m_bAutoDelete = FALSE;
m_pThread->ResumeThread();
// ...
m_bAbort = TRUE;
// ...
WaitForSingleObject(m_pThread->m_hThread, INFINITE);
delete m_pThread;
Regards,
Tobias
- Next message: Joseph M. Newcomer: "Re: Menu items become unexpectedly disabled"
- Previous message: Macca: "Automatic Start up of my application"
- In reply to: Mike Gleason Jr Couturier: "WaitForSingleObject freezes application"
- Messages sorted by: [ date ] [ thread ]
Relevant Pages
|