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/