【技巧点滴】线程创建后需要立即调用CloseHandle

    

     Closing a thread handle does not terminate the associated thread. To remove a thread object, you must terminate the thread, then close all handles to the thread

      创建线程后返回了线程句柄,新创建的线程内核对象的使用计数是2,一个是线程本身,一个是创建线程的线程,创建线程的线程closehandle后,新的线程的内核对象使用计数为1,当这个新线程结束运行后内核对象的使用计数还要减1,这时内核对象的使用计数是0,则系统会自动删除新线程的内核对象,这是正常的处理流程。
     你如果不显示的调用closehandle,则新线程结束运行后,由于内核对象使用计数为1,所以不会删除内核对象,会造成内存泄露,不过当整个进程结束时操作系统会自动关闭该进程的所有的内核对象包括这个新线程的内核对象,所以你不调用closehandle问题不大,只是在你的进程运行的时候会造成内存泄露,进程结束后系统是会自动清理的。

    《windows核心编程》上说调用closehandle(HANDLE)表示创建者放弃对该内核对象的操作。如果该对象的引用对象记数为0就撤消该对象。而ExitThread的功能是终止一个线程,它所接受的参数是一个线程的退出码,ExitThread是推荐使用的结束一个线程的方法,当调用该函数时,当前线程的栈被释放,然后线程终止,相对于TerminateThread函数来说,这样做能够更好地完成附加在该线程上的DLL的清除工作。

     creating   a   new   process   causes   the   system   to   create   a   process   kernel   object     and   a   thread   kernel   object.   At   creation   time,   the   system   gives   each   object     an   initial   usage   count   of   1.   Then,   just   before   CreateProcess   returns,   the    function   opens   the   process   object   and   the   thread   object   and   places   the     process-relative   handles   for   each   in   the   hProcess   and   hThread   members   of    
  the   PROCESS_INFORMATION   structure.   When   CreateProcess   opens   these   objects   internally,   the   usage   count   for   each   becomes   2.

    CreateThread后那个线程的引用计数不是1,调用CloseHandle只是说自己对这个线程没有兴趣了,线程还是正常运行的

HANDLE threadhandle = CreateThread(NULL, 0, RecvThreadProc, NULL, NULL, NULL); 

CloseHandle(threadhandle); 

 

handle 可以是一下句柄:

Change notification 
Console input 
Event 
Job 
Memory resource notification 
Mutex 
Process 
Semaphore 
Thread 
Waitable timer

你可能感兴趣的:(【技巧点滴】线程创建后需要立即调用CloseHandle)