1

Here is a code snippet from Network Programming for Microsoft Windows:

...
// Determine how many processors are on the system.
GetSystemInfo(&SystemInfo);

// Create worker threads based on the number of
// processors available on the system. For this
// simple case, we create one worker thread for each
// processor.

for (int i = 0; i < SystemInfo.dwNumberOfProcessors; i++)
{
    // Create a server worker thread, and pass the
    // completion port to the thread. NOTE: the
    // ServerWorkerThread procedure is not defined
    // in this listing.

    HANDLE ThreadHandle = CreateThread(NULL, 0, ServerWorkerThread, CompletionPort, 0, NULL);

    // Close the thread handle
    CloseHandle(ThreadHandle);
}
...

What I don't understand is why the sample closes the thread handles straightaway. Is it not necessary to store them (for example in a std::vector) so you can terminate all the worker threads later when exiting your program?

jpen
  • 2,129
  • 5
  • 32
  • 56
  • Only if you actually want to explicitly terminate all the worker threads later when exiting your program. If you don't need to, then there is no point in keeping any such reference. In IOCP servers, I don't attempt any such cleanup. – Martin James Jul 26 '12 at 17:42
  • More to the point, only if you need the thread handle for a thread-specific operation, such as TerminateThread (NEVER do that, btw) or a much more likely reason: WaitForSingle/MultipleObject(s). The handle is signaled in the latter case when the thread terminates. If you don't need it for this or any operation like this, you need to close it, preferably right after you open it. – WhozCraig Sep 06 '12 at 20:36

1 Answers1

2

It is not necessary. From msdn on CloseHandle:

Closing a thread handle does not terminate the associated thread or remove the thread object. Closing a process handle does not terminate the associated process or remove the process object. To remove a thread object, you must terminate the thread, then close all handles to the thread. For more information, see Terminating a Thread. To remove a process object, you must terminate the process, then close all handles to the process. For more information, see Terminating a Process.

In practive self contained threads are often created with their handles immediately closed, this allowing resource release when thread exits.

yuri kilochek
  • 12,709
  • 2
  • 32
  • 59
  • @yuri-But how do you terminate the threads explicitly without having their handles? – jpen Jul 26 '12 at 15:01
  • @jpen - I don't think thats possible unless you implement some mechanism to signal your threads to exit (which you should do anyway as TerminateThread is a really bad thing that doesn't clean up resources) – yuri kilochek Jul 26 '12 at 15:11
  • Yes, you would use a separate variable/event/whatever to signal the threads to terminate when needed. – Remy Lebeau Jul 26 '12 at 21:03