views:

51

answers:

1

Hi. I've narrowed down a problem.

  1. I create a simple Dialog app with VC++ 6.0.
  2. I start a thread before the main dialog DoModal() is called
  3. I exit the application - sometimes the app shuts down immediately, other times it hangs for 10 seconds or so

What causes this? I have tried _beginthread(), _beginthreadex() and AfxBeginThread(). They all do the same thing.

If I add a Sleep(50) after the DoModal() call (when the GUI has finished processing), the program seems to terminate without problem every time.

What caused me to narrow down this problem was that I have a Win32 DLL that does the same thing. My DLL has a thread and I noticed that my applications using this DLL would sometimes take a while to stop. Eliminating the DLL and creating the simplest of programs resulted in the same thing - which is what I have described above.

Below is the code which I have added to a bog-standard MFC Dialog app:

UINT Thread( void * )
{
  for( ;; )
  {
    Sleep( 50 );
  }

  AfxEndThread( 0 );
  return 0;
}

/////////////////////////////////////////////////////////////////////////////
// CThreadTest2App initialization

BOOL CThreadTest2App::InitInstance()
{
    AfxEnableControlContainer();

    // Standard initialization
    // If you are not using these features and wish to reduce the size
    //  of your final executable, you should remove from the following
    //  the specific initialization routines you do not need.

#ifdef _AFXDLL
    Enable3dControls();         // Call this when using MFC in a shared DLL
#else
    Enable3dControlsStatic();   // Call this when linking to MFC statically
#endif

  AfxBeginThread( Thread, 0 );

    CThreadTest2Dlg dlg;
    m_pMainWnd = &dlg;
    int nResponse = dlg.DoModal();

  //Sleep( 50 );   // Works when I add this ?????

    if (nResponse == IDOK)
    {
    }
    else if (nResponse == IDCANCEL)
    {
    }

    // Since the dialog has been closed, return FALSE so that we exit the
    //  application, rather than start the application's message pump.
    return FALSE;
}

Can somebody please help me in shutting down my app properly? What I'm ultimately trying to do is provide a way of letting my DLL close down without it being explicitly told to stop the thead via the calling application.

Thanks Paul

A: 

Well, you have and endless loop in your thread-function and never get to the call of AfxEndThread!

If you want to stop the thread from outside, you have to code a signalling mechanism into it, and check inside the loop if you have to stop.

dwo
OK - so why does it vary? You add a test for a flag inside the thread and set the flag after the dialog completes - you will get the same problem. It may take 3-4 executions to see what I mean, but give it a go.
Sparky
But currently your thread gets killed by the OS, not by yourself. And this may vary in the time needed.
dwo