我有一个主线程,它接收需要一些时间的操作。所以我创建一个线程并将工作委托给它。当主线程接收作业时,将调用此执行函数。每个作业都执行此执行。
Return_type execute( Arguments_here) {
// if a file read case
DWORD threadId;
HANDLE hThread = CreateThread(
NULL, // default security attributes
0, // use default stack size
MyAsyncFileRead, // thread function name
details, // argument to thread function
0, // use default creation flags
&threadId); // returns the thread identifier
// else do other work
}
现在,由于我不想在主线程上等待,因此我不调用 WaitForSingleObject。 [我对Windows线程的了解很低。所以如果这不是必需的,请原谅我]
如果我等待线程关闭,它将等待我的主线程。我不想那样做。
那么我什么时候调用 CloseHandle ?
当一个人手头上有大约 10 个作业,并且创建了 10 个线程,然后等待所有 10 个线程完成时,那么 wait_for_multiple_objects 然后在每个句柄上调用 CloseHandle 看起来不错。
但这种情况我该怎么办呢?
[我认为这个问题与所有操作系统相关,因此也标记它们。 ]
如果你真的不关心等待线程,你确实可以在创建线程后立即关闭句柄。
但是,我强烈建议不要这样做。你应该always等待线程退出(最好以干净、定义良好的方式)。如果没有提前完成,请等待程序退出时生成的每个线程。总是如此,无一例外。
不要离开main
不知道其他线程是否仍在运行。如果需要的话,用艰难的方式杀死他们(不过最好让他们以受控的方式优雅地退出,然后等待)。
If you don't wait for threads to finish, you may see weird crash-on-exit conditions. Or worse, you might not see them, and only have users/customers complain that one in a hundred times the config file gets corrupted (or worse, a data file of theirs)1. Now imagine that they are able to demonstrate step-by-step what they're doing, and you can tell that they do everything correctly, and there is no way something could go wrong.
Good luck figuring out that the crash is due to a still-running worker thread accessing some object (or global state) which was just deallocated by the exiting main thread, either explicitly or implicitly by the CRT.
当然,您的立场可能是工作线程将在程序完成之前很久就退出,所以为什么要麻烦呢。然而,那就是玩俄罗斯轮盘赌。
1This is not fiction, but something I've actually seen happen before.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)