zhengchl
zhengchl

Reputation: 341

when all thread kernel object handles is closed, does the thread still running

I'm curious that when all thread kernel object handles is closed, does the thread still running in Win32?

So I write a simple test codes like

#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;
}

and the output is

enter image description here

It looks like when all handle is closed, the thread is still running. However, msdn says that "An object remains in memory as long as at least one object handle exists". This is strange.

Upvotes: 0

Views: 103

Answers (2)

David Heffernan
David Heffernan

Reputation: 613382

The text you quote:

An object remains in memory as long as at least one object handle exists.

does not apply to thread execution. Threads execute until they are finished. And then they stop executing. The thread handle merely provides a mechanisn for you to query for exit codes, to wait until signaled, to force termination etc.

So, closing the final handle to a thread will not terminate the thread.

Upvotes: 2

Jonathan Potter
Jonathan Potter

Reputation: 37192

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.

Upvotes: 2

Related Questions