A sleep in thread causes memory leak A sleep in thread causes memory leak multithreading multithreading

A sleep in thread causes memory leak


It sounds like the worker thread is not given a chance to close itself properly after your app closes, since the process ends before it exits. The operating system is usually pretty good at cleaning up resources on its own, so it may not be a problem. However, it's probably best if you wait for that thread to exit before allowing the application to shut down. Though it sounds like that that will cause a 4 second delay in the shutdown of your app.

If that's unacceptable, you will have to add some mechanism to the thread, to receive the shutdown event from the apps main thread. For example, if you replace the worker threads "sleep", with a WaitForSingleObject of an event:

DWORD res = WaitForSingleObject(    shutdownEvent,    4000); // timeoutif(res == WAIT_OBJECT_0){    // received the shutdownEvent, exit    return 0;}// The delay has elapsed, continue with rest of thread.. . .

Then, when your are shutting down in your main thread, set the event, then wait for the thread to exit, it should exit almost immediately:

SetEvent(this->shutdownEvent);WaitForSingleObject(pThread->m_hThread, INFINITE); // pThread is returned from AfxBeginThread


You should shutdown your threads gracefully before your process goes away. You can either have the main thread wait for the other thread(s) to exit or have the main thread signal the other thread(s) to exit.


68 bytes?

If the application does actually shut down, ie. has disappeared from the task manager 'Applications' and 'Processes', and the only effect of this 'leak' is to issue a debug message on early close, just turn the debug off and forget about it.

It's likely an abberation of MFC shutdown, some struct that cannot be safely freed during shutdown and is left around for the OS to clean up.

With the 99.9% of apps that are not continually restarted/stopped, a 68-byte leak on shutdown, even if it was not cleaned up, would not influence the operation of a Windows machine in any noticeable way between the reboot intervals enforced every 'Patch Tuesday'.

I'm sure you have plenty more bugs with more serious effects to deal with. If not, you can have some of mine!

Rgds,Martin