0

我很好奇,当所有线程内核对象句柄都关闭时,线程是否还在 Win32 中运行?

所以我写了一个简单的测试代码,比如

#include <cstdio>
#include <Windows.h>
#include <process.h>

unsigned int __stdcall thread1_main(void* p)
{
    while(1)
        printf("thread1 is running!\n");
    return 0;
}

int main()
{
    HANDLE h = (HANDLE)_beginthreadex(NULL, 0, thread1_main, NULL, 0, NULL);
    CloseHandle(h);
    while(1)
        printf("main thread is running!\n");
    return 0;
}

输出是

在此处输入图像描述

看起来当所有句柄都关闭时,线程仍在运行。但是,msdn 说“只要至少存在一个对象句柄,一个对象就会保留在内存中”。这很奇怪。

4

2 回答 2

2

Yes, the thread will run until it exits (by returning from its initial thread procedure), it is forcibly terminated (via TerminateThread or _endthread(ex)), or its parent process exits. Whether handles to the thread exist or not is irrelevant.

If you think about it, it could never work any other way - since you can wait on a thread handle to determine if it has exited or not, by definition the thread lifetime is unrelated to the lifetime of the handle.

于 2013-04-09T07:55:44.363 回答
2

你引用的文字:

只要至少存在一个对象句柄,一个对象就会保留在内存中。

不适用于线程执行。线程执行直到完成。然后他们停止执行。线程句柄只是为您提供了一种机制来查询退出代码、等待发出信号、强制终止等。

因此,关闭线程的最终句柄不会终止线程。

于 2013-04-09T07:59:14.357 回答