多线程的问题

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();
}
...全文
185 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
Teose 2007-08-28
  • 打赏
  • 举报
回复
多些楼上二位,分已送出~
Teose 2007-08-28
  • 打赏
  • 举报
回复
呵呵,多谢jasonshark(没暑假了...) 的指教~
jasonshark 2007-08-28
  • 打赏
  • 举报
回复
To make things simple: handle is returned for using in user mode
So references to the object in kernel mode is not counted as a "handle", but as a "reference"

for example, the sheduler in kernel need a reference for sheduling, right?
Teose 2007-08-28
  • 打赏
  • 举报
回复
多谢nkgd(长歌天下),我只看了核心编程的前几章,在3.1.1 内核对象的使用计数中提到:当一个对象刚刚创建时,它的使用计数被置为1。因此就认为线程内核对象也是这样的,没想到它的初始计数是2,呵呵,多谢了~

to jasonshark(没暑假了...),也多谢你,不过对 handle count 和 reference count的区别还不是很了解~
jasonshark 2007-08-28
  • 打赏
  • 举报
回复
distinguish between the handle count and the reference count.

reference count can be greater than handle count -- this is always the truth, or almost.
when to remove a kernel object, that's decided by the object manager, looking at the object's reference count, not handle count.
nkgd 2007-08-28
  • 打赏
  • 举报
回复
看windows核心编程,6.4以及6.6

6.4:当CreateThread被调用时,系统创建一个线程内核对象。该线程内核对象不是线程本身,而是操作系统用来管理线程的较小的数据结构。………………这与进程和进程内核对象之间的关系是相同的。

6.6:调用CreateThread可使系统创建一个线程内核对象。该对象的初始使用计数是2(在线程停止运行和从CreateThread返回的句柄关闭之前,线程内核对象不会被撤销)。

24,855

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 工具平台和程序库
社区管理员
  • 工具平台和程序库社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧