c++ - 如何安全地关闭线程?

标签 c++ pthreads

     pthread_create(&thread, NULL, AcceptLoop, (void *)this);

我已经这样声明,并且在 AcceptLoop 函数内部我有无限 while 循环。我想在服务器关闭时关闭此线程。我已经阅读了 pthread_cancel 和 pthread_join,但我不确定哪个更好更安全。我想听听一些详细的说明或教程。提前致谢。

最佳答案

你什么都不用做,只要从线程函数返回就可以干净利落地结束线程。您也可以调用 pthread_exit() 但我宁愿返回。 pthread_cancel() 可怕且复杂/难以正确处理。如果可能的话,保持清醒。 pthread_join() 如果您想知道线程何时结束并且对 return 值感兴趣,则最需要。

糟糕,我错了。已经有一段时间了。为了让我说的是真的,你必须脱离你的线程。否则你需要调用 pthread_join:

Either pthread_join(3) or pthread_detach() should be called for each thread that an application creates, so that system resources for the thread can be released. (But note that the resources of all threads are freed when the process terminates.)

http://www.kernel.org/doc/man-pages/online/pages/man3/pthread_detach.3.html

关于c++ - 如何安全地关闭线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6352805/

相关文章:

c++ - 在 C++ 中为游戏对象设计类层次结构

c++ - 使用 C++11 的基于范围的正确方法是什么?

C++ P线程 : Algorithm to run N threads simultaneously when >N threads must be run each iteration

c++ - 在函数中增加数组索引

c++ - 拖动分隔栏以调整两个面板的大小时,内容(或背景)仍然存在

c - 线程已创建但无法相应工作

c - 如何在 Linux 中使用 POSIX pthreads 将整数从文件写入缓冲区?

c++ - Pthreads 和动态内存

c - 如何使用 pthreads 在 C 中的 udpclient 中发送和接收

c++ - 编译器如何知道使用模板特化而不是它自己的实例化?