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.
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.
When you kill process, everything that process owns, including threads is also killed. The Terminated property is irrelevant. The system just kills everything.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With