[RESOLVED] Avoiding memory leaks when multithreading?
Hello, again fellow coders.
I've written a test app that has 3 buttons, each one creating and executing a separate thread. Each thread has its own STATIC control where it counts to 10.
My question is, as I want the 3 threads to run at the same time with 1 sec between each run, I cannot use the WaitForSingleObject or other functions which waits for one thread to finish before the next one starts, because then they wouldn't execute simultaneously!
This brings me another problem, as I do not know when the thread finishes. So I cannot call CloseHandle on them which in the end leaks memory right?
How do I ensure that I close and clear the thread (ExitThread does this when the thread returns right?) properly while maintaining the ability to not wait on any thread to finish so my program GUI won't block. I want to close the thread when it's finished (how do I know when it is?).
I came up with a somewhat dull approach; I send a postmessage just before the thread returns with a message defined by me, and then I catch the message in my WndProc and call CloseHandle there. But this doesn't work does it, since the thread never reaches the return statement before I close the handle?
Re: Avoiding memory leaks when multithreading?
I don't see any memory leak problem here, and you can close thread handle after creating it, clsong thread handle does not terminate/stop the thread.
Re: Avoiding memory leaks when multithreading?
Yes, you can post a message to the main window from your threads, just before the last line (which has to be a simple return 0, no ExitThread needed).
From you main window procedure, get the message and call CloseHandle. Finally, get WM_DESTROY and call WaitForMultipleObjects on the thread handles that haven't expired yet (and/or send them a message to notify about program termination).
If you don't want to worry about thread termination, just close their handle as soon as you create them (as Krishnaa has already suggested).
Re: Avoiding memory leaks when multithreading?
Does this mean that if I close the thread handle while the thread is running, it will be cleared from the system once it returns (exits)?
I read on MSDN that the thread is only removed completely from system once the (last?) handle to it is closed. So if I close this last handle before the thread returns it doesn't stay in the system once it returns does it?
Re: Avoiding memory leaks when multithreading?
If you close the thread handle, only the handle is closed not the thread. Thread can exist/complete on it's own Or can be terminated by calling TerminateThread call.
usually people forget to close thread handle and the handle gets leaked this way, handle being one kernel resource it should be closed.
Re: Avoiding memory leaks when multithreading?
Oh I see. I was just worried about forgetting to close something.
Thanks for the nice replies, I really appreciate your time.
Re: Avoiding memory leaks when multithreading?