CloseHandle 函式的使用

2021-06-17 01:20:15 字數 940 閱讀 6691

很多程式在建立執行緒都這樣寫的:

............

threadhandle = createthread(null,0,.....);

closehandel(threadhandle );

。。。。。

這不是剛好建立又關閉了嗎?執行緒怎麼執行呢?

答: 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.

引自msdn

1,執行緒和執行緒控制代碼(handle)不是乙個東西,執行緒是在cpu上執行的.....(說不清楚了),執行緒控制代碼是乙個核心物件。我們可以通過控制代碼來操作執行緒,但是執行緒的生命週期和執行緒控制代碼的生命週期不一樣的。執行緒的生命週期就是執行緒函式從開始執行到return,執行緒控制代碼的生命週期是從createthread返回到你closehandle()。

2,所有的核心物件(包括執行緒handle)都是系統資源,用了要還的,也就是說用完後一定要closehandle關閉之,如果不這麼做,你系統的控制代碼資源很快就用光了。

3,如果你createthread以後需要對這個執行緒做一些操作,比如改變優先順序,被其他執行緒等待,強制termatethread等,就要儲存這個控制代碼,使用完了在closehandle。如果你開了乙個執行緒,而不需要對它進行如何干預,createthread後直接closehandle就行了。

所以closehandel(threadhandle );

只是關閉了乙個執行緒控制代碼物件,表示我不再使用該控制代碼,即不對這個控制代碼對應的執行緒做任何干預了。並沒有結束執行緒。

如果你覺得多了乙個變數,也可以寫為:

closehandel(createthread(null,0,.....));

CloseHandle函式的使用

很多程式在建立執行緒都這樣寫的 threadhandle createthread null,0,closehandel threadhandle 這不是剛好建立又關閉了嗎?執行緒怎麼執行呢?closing a thread handle does not terminate the associa...

CloseHandle 函式的使用

很多程式在建立執行緒都這樣寫的 threadhandle createthread null,0,closehandel threadhandle 這不是剛好建立又關閉了嗎?執行緒怎麼執行呢?答 closing a thread handle does not terminate the assoc...

CloseHandle 函式的使用

很多程式在建立執行緒都這樣寫的 threadhandle createthread null,0,closehandel threadhandle 這不是剛好建立又關閉了嗎?執行緒怎麼執行呢?答 closing a thread handle does not terminate the assoc...