Search code examples
multithreadingpthreadsatexit

Does atexit wait for other threads to die?


Are the functions registered with atexit() the last functions to be executed? Is it possible that other threads at this time are still running?


Solution

  • Are the functions registered with atexit() the last functions to be executed?

    The atexit() calls will be executed in the main thread after the main thread finishes executing. Other than that, no guarantees are made.

    Is it possible that other threads at this time are still running?

    Yes, if you haven't taken steps to stop the other threads and join() them before main() returns. In general you want to do an explicit, controlled shutdown of all of your threads, as the C (or C++) runtime will not do it for you, and letting them continue to run even as the main() thread is exiting introduces the possibility that they will try to access resources that main() has deallocated as part of its shutdown sequence, which will invoke undefined behavior (often experienced as an occasional, not-easily-reproducible crash during program shutdown)