Mark
Mark

Reputation: 1801

POSIX threads and exiting from a thread

I have two threads, communicating with each other; each thread employs 'while(1) ..'. Now I need to let the threads exit upon a specific condition met, and therefore finish the application.

My question: is it safe to just 'return (NULL)' from the thread, or do I have to use 'pthread_exit' or 'pthread_join' functions as well?

Upvotes: 4

Views: 1364

Answers (2)

Jonathan Leffler
Jonathan Leffler

Reputation: 753525

It is safe to return null from the thread functions; the code that waits for them should be OK.

POSIX says of pthread_exit():

An implicit call to pthread_exit() is made when a thread other than the thread in which main() was first invoked returns from the start routine that was used to create it.

You do need something to wait for the thread with pthread_join() unless the thread was created with the detached attribute or detached later with pthread_detach().

Upvotes: 4

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215193

Calling pthread_exit(NULL) and returning NULL at the end of the thread's initial function should be equivalent. However, doing either of these alone will lead to a resource leak. To avoid that, you must either call pthread_join on the thread from another thread, or put the thread in the detached state by calling pthread_detach on it or setting it to start in the detached state before creating it.

Upvotes: 3

Related Questions