简体   繁体   English

如何安全地关闭线程?

[英]How do I close a thread safely?

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

I have declared like this and inside of the AcceptLoop function I have infinity while loop.我已经这样声明了,并且在 AcceptLoop function 内部我有无限的while循环。 I'd like to close this thread when the server is closed.我想在服务器关闭时关闭这个线程。 I have read pthread_cancel and pthread_join but I am not sure which one is better and safer.我已阅读 pthread_cancel 和 pthread_join 但我不确定哪个更好更安全。 I would like to hear some detailed instructions or tutorials.我想听听一些详细的说明或教程。 Thanks in advance.提前致谢。

You don't need to do anything, just returning from the thread function will end the thread cleanly.您无需执行任何操作,只需从线程 function 返回即可干净地结束线程。 You can alternatively call pthread_exit() but I'd rather return.您也可以调用pthread_exit()但我宁愿返回。 pthread_cancel() is scary and complicated/hard to get right. pthread_cancel()是可怕的和复杂的/很难做对。 Stay clear if possible.尽可能保持清晰。 pthread_join() is mostly needed if you want to know when thread finishes and are interested in the return value.如果您想知道线程何时完成并对return值感兴趣,则最需要pthread_join()

Ooops, I'm wrong.哎呀,我错了。 It's been some time.已经有一段时间了。 In order for what I said to be true, you must detach from your thread.为了让我说的是真的,你必须脱离你的线程。 Otherwise you'll need to call pthread_join:否则你需要调用 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.应为应用程序创建的每个线程调用 pthread_join(3) 或 pthread_detach(),以便释放线程的系统资源。 (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 http://www.kernel.org/doc/man-pages/online/pages/man3/pthread_detach.3.html

I believe you would like to exit the worker thread by signalling from the main thread.我相信您想通过从主线程发出信号来退出工作线程。

Inside AcceptLoop instead of looping infinitiely you loop on a condition, you can set the condition through your main thread, You will have to use some synchronization for this variable.AcceptLoop内部,不是无限循环,而是在条件上循环,您可以通过主线程设置条件,您必须为此变量使用一些同步。 Once the variable is set from main thread the worker thread AcceptLoop would break out and you can then call pthread_exit .一旦从主线程设置变量,工作线程AcceptLoop就会中断,然后您可以调用pthread_exit

if you would like your main thread to wait for child thread to exit you can use pthread_join to do so.如果您希望您的主线程等待子线程退出,您可以使用pthread_join来执行此操作。

In general, A child thread can exit in three conditions:一般来说,子线程可以在三种情况下退出:

  1. calling pthread_exit .调用pthread_exit
  2. calling pthread_cancel .调用pthread_cancel
  3. The thread function returns.线程 function 返回。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM