![](/img/trans.png)
[英]Does thread need to get the ownership of the mutex to close the handle of the mutex
[英]CInternetSession close thread handle
我嘗試創建一個簡單的應用程序,該程序在FTP服務器上寫入/讀取文件。 我創建一個線程
HANDLE hThread;
unsigned threadID;
hThread = (HANDLE)_beginthreadex( NULL, 0, &foo, NULL, 0,NULL );
CloseHandle( hThread );
函數foo()會像這樣創建新的Internet會話
CInternetSession session(_T("Session"));
但是在調用CInternetSession session(_T(“ Session”))之后,線程結束
有辦法解決嗎?
您需要您的線程函數等待事件或進入循環以防止函數結束。 當該函數退出時,線程將死亡。
例如,您可以使用Windows事件API:
void foo(){
// The Event exitSessionEvent must be declared somewhere where the controlling
// thread can access it. This might be a global event for example (in a namespace).
// You must initialise it using CreateEvent.
CInternetSession session(_T("Session"));
// ... do some stuff ....
WaitForSingleObject(exitSessionEvent, INFINITE);
session.Close(); //Done so cleanup
}
現在線程函數將不會退出,直到設置了“ exitSessionEvent”事件(由其他人)。
您還可以使用某種標志並具有while(flag)
循環,但是事件是在我認為的多線程應用程序中表達自己的更清晰的方法。
同樣,創建線程的線程不應成為關閉該線程的線程,除非它等待結束。 在關閉線程句柄之前,您似乎並沒有等待新線程完成。 同樣,如果使用事件,則可以執行以下操作:
HANDLE hThread;
unsigned threadID;
hThread = (HANDLE)_beginthreadex( NULL, 0, &foo, NULL, 0,NULL );
WaitForSingleObject(hThread, INFINITE);
CloseHandle( hThread );
在關閉句柄之前,它將等待線程完成。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.