Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Who's responsibility is it to call CloseHandle() for Thread handle

I have a class Class in which there's a member property HANDLE handle to a thread (We can assume it is set to NULL at that point) . at some point , a method within Class dispatches one of it's own methods Class::threaded() (using another function that is external to the class itself, but it doesn't really matter here) with CreateThread(). The calling thread will then may continue to other function outside of Class.

As CloseHandle() must be called for the HANDLE returned from CreateThread() , I was wondering if calling it from Class::threaded() just before it returns would be a decent solution.

like image 697
Edgar James luffternstat Avatar asked Nov 29 '22 11:11

Edgar James luffternstat


2 Answers

Two basic ways to deal with a thread. Commonly you're interested when the thread terminates, you'll need to keep the handle around so you can find out. And of course you'll close it after you detected termination. Or you don't care, fire-and-forget style, or have additional synchronization objects to signal that the thread function completed and/or you ask it to exit. In which case you simply close the handle as soon as you start it.

Do keep in mind that it is not necessary to keep the handle opened to keep the thread running, in case that's the source of the confusion.

like image 197
Hans Passant Avatar answered Dec 10 '22 16:12

Hans Passant


You receive a handle to the thread so you can manage it. If there is no need to it, you can call CloseHandle right away.

Closing the HANDLE will have no terminate the thread, so, it's secure to close it if nothing from the thread is of interest to you.

like image 30
fernando.reyes Avatar answered Dec 10 '22 15:12

fernando.reyes