【发布时间】:2012-07-25 04:21:13
【问题描述】:
这是来自Microsoft Windows 网络编程的代码sn-p:
...
// 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);
}
...
我不明白为什么示例会直接关闭线程句柄。是否不需要存储它们(例如在 std::vector 中),以便稍后退出程序时终止所有工作线程?
【问题讨论】:
-
仅当您确实想在以后退出程序时显式终止所有工作线程时。如果您不需要,那么保留任何此类参考是没有意义的。在 IOCP 服务器中,我不会尝试进行任何此类清理。
-
更重要的是,仅当您需要线程句柄以执行特定于线程的操作时,例如 TerminateThread(永远不要这样做,顺便说一句)或更可能的原因:WaitForSingle/MultipleObject(s) .在后一种情况下,当线程终止时,会发出句柄信号。如果您不需要它来执行此操作或任何类似的操作,则需要将其关闭,最好在打开后立即关闭。
标签: c++ sockets network-programming asyncsocket iocp