Reputation: 1147
I'm using CreateThread then TerminateThread to cancel threads. It seems like stack space is still allocated. Is there a way to deal with this? I am not using any form of dynamic memory calls such as malloc/new. Threads do not have to exit gracefully. 10 threads leave behind a whopping 5 MB of memory! The threads are all on varying parts of code, so is there a simple way to implement a interthread communication system which can tell them to all exit gracefully, and therefore reorient the stack?
Upvotes: 0
Views: 1137
Reputation: 66194
A non-auto-reset event and a WaitForMultipleObjects on your primary thread will do what you want. If you find yourself exceeding 64 concurrent worker threads, you'll have to retool to use a different approach, such as non-auto-reset event and a semaphore. There are literally dozens of ways to approach this problem, and countless examples on forums throughout the internet, as well as MS's examples in their distribution of Visual Studio. Start with those.
Upvotes: 3
Reputation: 17327
In most cases you should not use TerminateThread()
. If you create new threads in your application, it's your responsibility to make sure that those threads do exit gracefully. When you use TerminateThread()
, all kinds of resources may be left behind because this function simply terminates the thread without calling clean-up functions.
What you should do is use events (or other signaling methods) to tell your threads that they're supposed to shut down. When the thread internally receives the message (the event is signaled or a wait expires, etc.) the thread function can internally clean up and return. This way you'll exit your threads correctly and not leave a mess behind.
Upvotes: 11