Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I close a thread safely?

Tags:

c++

pthreads

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

I have declared like this and inside of the AcceptLoop function I have infinity while loop. 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. I would like to hear some detailed instructions or tutorials. Thanks in advance.

like image 781
codereviewanskquestions Avatar asked Jun 15 '11 03:06

codereviewanskquestions


People also ask

How do you end a thread in Java?

Modern ways to suspend/stop a thread are by using a boolean flag and Thread. interrupt() method. Using a boolean flag: We can define a boolean variable which is used for stopping/killing threads say 'exit'. Whenever we want to stop a thread, the 'exit' variable will be set to true.

Does killing a process kill all threads?

When you kill process, everything that process owns, including threads is also killed. The Terminated property is irrelevant. The system just kills everything.


1 Answers

You don't need to do anything, just returning from the thread function will end the thread cleanly. You can alternatively call pthread_exit() but I'd rather return. pthread_cancel() is scary and complicated/hard to get right. Stay clear if possible. pthread_join() is mostly needed if you want to know when thread finishes and are interested in the return value.

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:

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

like image 73
MK. Avatar answered Oct 28 '22 22:10

MK.