Geeks With Blogs
Prabhu Kumar a tech twaddler..
I was browsing through some code when I came across a line of code which said:

CloseHandle( CreateThread(NULL, 0, PeculiarThreadProc, NULL, 0, NULL) );

And I thought, wait a minute, is he closing the handle to the thread immediately after its created. I pinged my TL and he said the thread will continue to run until it terminates. I thought I had read in documents that a thread will terminate when the last handle to it was closed and here it was the last and only handle to the thread. A closer look at the documentation made it clear,

"The thread object remains in the system until the thread has terminated and all handles to it are closed through a call to Closehandle."

I had missed the 'and'. Anyways, to kill my curiosity for good I went ahead and tested the following code,

int WINAPI WinMain(HINSTANCE hInstance,
                   HINSTANCE hPrevInstance,
                   LPTSTR    lpCmdLine,
                   int       nCmdShow)
{
    CloseHandle( CreateThread(NULL, 0, PeculiarThreadProc, NULL, 0, NULL));

     while(1)
     {
          Sleep(1000);
     }

    return 0;
}

DWORD WINAPI PeculiarThreadProc(void *lPtr)
{
    DWORD tick;
    while(1)
    {
        tick = GetTickCount();
        printf("Tick count:%u\r\n", tick);
        Sleep(1000);       
    }
}

And as expected the thread kept running in all its glory.

Suppose we modify our program a little as below,

int WINAPI WinMain(HINSTANCE hInstance,

                   HINSTANCE hPrevInstance,
                   LPTSTR    lpCmdLine,
                   int       nCmdShow)
{
    CreateThread(NULL, 0, PeculiarThreadProc, NULL, 0, NULL);
    
     while(1)
     {
          //do nothing
          Sleep(1000);
     }

    return 0;
}

DWORD WINAPI PeculiarThreadProc(void *lPtr)
{
        printf("PeculiarThreadProc");
        Sleep(100);       
}

So in this case, the thread terminates but the handle to the thread is not closed. So does that mean that the thread object remains in the system? The answer is yes, and the thread object will exist in signaled state. And of course, if the main thread itself exits then all hope is lost (;

Posted on Tuesday, September 22, 2009 12:32 PM General | Back to top


Comments on this post: CloseHandle(CreateThread(...));

# re: CloseHandle(CreateThread(...));
Requesting Gravatar...
When CreatThread but do not close handle,this will be object memory leak...

your code example is nice,good job :)
Left by IicFox on Oct 14, 2009 9:30 PM

Your comment:
 (will show your gravatar)


Copyright © TechTwaddle | Powered by: GeeksWithBlogs.net