gpt4 book ai didi

c++ - 如何正确关闭为使用 IOCP 创建的工作线程

转载 作者:行者123 更新时间:2023-11-30 04:26:15 25 4
gpt4 key购买 nike

这是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);
}
...

我不明白的是为什么示例会立即关闭线程句柄。是否没有必要存储它们(例如在 std::vector 中)以便您稍后可以在退出程序时终止所有工作线程?

最佳答案

没有必要。来自 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.

在实践中,自包含线程通常在其句柄立即关闭的情况下创建,这允许在线程退出时释放资源。

关于c++ - 如何正确关闭为使用 IOCP 创建的工作线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11671699/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com