Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top