How do I close a thread safely?
pthread_create(&thread开发者_如何学JAVA, 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.
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
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. Once the variable is set from main thread the worker thread AcceptLoop
would break out and you can then call pthread_exit
.
if you would like your main thread to wait for child thread to exit you can use pthread_join
to do so.
In general, A child thread can exit in three conditions:
- calling
pthread_exit
. - calling
pthread_cancel
. - The thread function returns.
精彩评论