我正在寻找一个旧的C++应用程序中的一些随机崩溃。使用Sysinternals(系统工具集合)进程浏览器,我注意到应用程序正在丢失句柄,并提取了确切的情况,即程序在一个非常短的代码片段中丢失句柄。
DWORD WINAPI MyTestThread( void* PThread)
{
_endthreadex(0);
return 0;
}
int WINAPI WinMain( HINSTANCE, HINSTANCE, LPSTR PParameter, int)
{
for (int i=0;i<10000;i++)
{
unsigned int threadID;
HANDLE hThread= (HANDLE)_beginthreadex( (void*)NULL, (unsigned int)32768, (unsigned int (__stdcall *)(void *))MyTestThread, (void*)NULL, (unsigned int)0, &threadID);
WaitForSingleObject((HANDLE)hThread, 1000);
CloseHandle((HANDLE)hThread);
}
return 0;
}
My problem: I can t figure out what s wrong with this code. It loses exactly 5 handles on every iteration, but it looks OK to me.
Funny thing: it seems not to lose handles on windows vista, but I d be very surprised if this should be a bug in windows 7.
[更新] 我尝试使用 _beginthread/_endthread 和 CreateThread/ExitThread,这两个和 _beginthreadex 一样都会失去5个句柄。
【第二次更新】代码如预期运行。所有返回值都很好。只是像没有明天一样失去句柄。
[3rd Update] Big new Info The code only loses handles, if compiled with /clr! And more, if I call GC::Collect() on each iteration the handles will be reclaimed!
So, how do I find what clr-objects are being collected there?