多线程的问题
Teose 2007-08-28 09:39:34 我用_beginthreadex创建了一个新线程之后,马上就CloseHandle掉,线程此时并没有被撤消。
我的问题是:当CloseHandle线程的句柄后,此线程对象的使用计数应该降为0了,在《Windows核心编程》3.2.2 中提到:该函数(CloseHandle)首先检查调用进程的句柄表,以确保传递给它的索引(句柄)用于标识一个进程实际上无权访问的对象。如果该索引是有效的,那么系统就可以获得内核对象的数据结构的地址,并可确定该结构中的使用计数的数据成员。如果使用计数是0,该内核便从内存中撤消该内核对象。
所以,为什么我在调用CloseHandle后,内核对象没有被撤消,而是等线程函数结束后该线程才结束?
请高人赐教!
代码如下:
unsigned Counter;
unsigned __stdcall SecondThreadFunc( void* pArguments )
{
printf( "In second thread...\n" );
while ( Counter < 1000000000 )
{
Counter++;
}
printf( "Counter should be 1000000000; it is-> %d\n", Counter );
// 显示调用结束进程函数
_endthreadex( 0 );
return 0;
}
void main(void)
{
HANDLE hThread;
unsigned threadID;
printf( "Creating second thread...\n" );
// Create the second thread.
hThread = (HANDLE)_beginthreadex( NULL, 0, &SecondThreadFunc, NULL, 0, &threadID );
// Destroy the thread object.
CloseHandle( hThread );
printf("please enter a char: \n");
getchar();
}