Click to See Complete Forum and Search --> : The Thread and it's Handle


NoHero
December 29th, 2004, 08:11 AM
Hi Folks,

I have a very dumm question. I help somebody with his project and he has the problem that he creates threads but never closes its handle. So after several hours of running he will run out of resources for his threads. Since I read


The thread object remains in the system until the thread has terminated and all handles to it have been closed through a call to CloseHandle.


this in MSDN I try to figure out ways how to close all the thread handles. It creates threads depending on the operation to be done. Let's say the client needs some calculation to be done, only if the calculation is bigger than X it will create a thread to handle it. But how do I close the threads handle, returned by CreateThread()? Shall I give it the thread procedure and he should close it before the thread returns? Shall I introduce some kind of thread garbage collection that has every handle in an array and waits for them to exit to close their handle? It's just a design question, so please help me folks.

I think I should add something: It is not my project though. Our school administrator wrote that in the holi days to handle the students "misfortunes" ;) and I think he has never heard about thread pooling. But in that case it doesn't matter anyway because the project is far too big to make a general redesign. So I need to solve the problem the way described above. If I would have written this it would include a thread pool but ....

Thanks in Advance, Best Regards
Florian

kirants
December 30th, 2004, 11:57 AM
HANDLE hThread = CreateThread(.. ThreadProc .. );
CloseHandle(hThread);

.. note that, though you close the handle here, it doesn't mean the thread is gonna be terminated. The threadProc will continue to run uninterrupted.

OReubens
December 31st, 2004, 09:41 PM
HANDLE hThread = CreateThread(.. ThreadProc .. );
CloseHandle(hThread);

.. note that, though you close the handle here, it doesn't mean the thread is gonna be terminated. The threadProc will continue to run uninterrupted.

Correct, but closing the handle immediately also means you can no longer use the thread handle itself.
Common uses for the handle are among others checking (from main thread) if the (worker) thread is still active or has stopped. Or waiting for the worker thread to end.

Typically, you should close the handle at the point in the code where you will no longer need to use the handle itself.
This could be directly following the CreateThread. It could be at the end of the thread's code itself. Or basicaly anywhere really, it's up to the program to decide.

NoHero
January 1st, 2005, 07:45 AM
Thanks guys ... :wave: