c++pthreads

What happens if you call exit(0) while other threads are still running?


Suppose a program has several threads: t1, t2, etc. These are using pthreads. The t2 thread is sitting in a loop reading from a stream and accessing a variable with static storage duration.

Now suppose t1 calls exit(0).

(Further details: I have a program doing this on a Unix-based system, and is compiled with g++. The program appears to occasionally be crashing on shutdown with a stack trace that indicates the static variable is not valid.)


Solution

  • I'm answering the question in the title of your question, not the 3 bullet points, because I think the answers to the bullet point questions are irrelevant to answer the actual question.

    Using exit when the program is in a random state - as you seem to suggest - is usually a rather brutal and undeterministic way to end a program even with a single thread. It doesn't even matter if the thread gets destroyed before object destruction or after, both ways result in nightmares. Remember, that each thread could be in a random state and accessing anything. And the stack objects of each thread will not be destroyed properly.

    See the documentation of exit to see what it does and doesn't clean up.

    The favored way I've seen to correctly shutdown a multithreaded program, is to make sure no thread is in a random state. Stop all the threads in some way or another, call a join on them where feasible, and from the last remaining thread call exit - or return if this happens in the main function.

    An incorrect approach I've seen often is to correctly dispose of some objects, close some handles, and generally try to do a proper shutdown until everything goes wrong, and then call terminate. I advise against that.