How to safely close the stream?

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

I stated so inside the AcceptLoop function, I have an infinite while loop. I would like to close this thread when the server is closed. I read pthread_cancel and pthread_join, but I'm not sure which one is better and safer. I would like to hear some detailed instructions or manuals. Thanks in advance.

+6
source share
2 answers

I believe that you want to exit the workflow by signaling from the main thread.

Inside AcceptLoop instead of looping endlessly on the loop, you can set the condition through your main thread, you will have to use some synchronization for this variable. After the variable is set from the main thread, the AcceptLoop worker thread AcceptLoop out and you can call pthread_exit .

if you want your main thread to wait for a child thread to exit, you can use pthread_join to do this.

In general, a child thread can exit from three conditions:

  • call pthread_exit .
  • call pthread_cancel .
  • The stream function is returned.
+1
source

You do not need to do anything, just returning from the stream function will complete the stream completely. You can also call pthread_exit() , but I'll be back soon. pthread_cancel() is scary and complex / hard to reach. Stay where you are. pthread_join() is mostly required if you want to know when the thread ends and is interested in the return value.

Oh, I'm wrong. It has been a while. In order for me to be true, you must disconnect from your thread. Otherwise, you need to call pthread_join:

Either pthread_join (3) or pthread_detach () should be called for each thread that the application creates, so that the system resources for the thread may 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

+2
source

Source: https://habr.com/ru/post/890569/


All Articles