Re: WaitForSingleObject freezes application

Tech-Archive recommends: Repair Windows Errors & Optimize Windows Performance

From: Tobias Güntner (fatbull_at_web.de)
Date: 07/18/04


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



Relevant Pages

  • Re: Using Doxygen with Angband
    ... that really we want them in the source files instead, ... Provides an example of a documentation style. ... BUG: Brief description of bug. ...
    (rec.games.roguelike.angband)
  • Re: Realtime Preemption, 2.6.12, Beginners Guide?
    ... > Which debugging options are most useful for testing purposes? ... The new options have made the BUG warning a bit more ... send the line "unsubscribe linux-kernel" in ...
    (Linux-Kernel)
  • Re: SharedCLibrary version
    ... > the availability of a 32-bit SCL on the A9. ... > a developer beta-testing the A9, you report the bug to Adv6 in the usual ...
    (comp.sys.acorn.programmer)
  • Re: Current JSON Proposal in ES4
    ... [snip about IE for-in enumeration bug] ... [snip about object enumeration is a bad idea] ... [snip about object serialization should not be an object property] ...
    (comp.lang.javascript)
  • Re: So long and thanks for all the fish.
    ... I did report it on the A9home list to the usual deafening silence. ... they have repeated to different people that *bug* reports ... StevePotts at blastzone DOT demon STOP co DOT uk ...
    (comp.sys.acorn.misc)