When the main thread exits, do other threads also exit?

You should use pthread_join() on each of the new threads, to inform the calling thread to wait on the sub-threads, suspending execution – and process exit – until those threads terminate.

Calling pthread_detach on the created threads won’t keep them around after a process exits. From the linux man page:

The detached attribute merely determines the behavior of the system when the thread terminates; it does not prevent the thread from being terminated if the process terminates using exit(3) (or equivalently, if the main thread returns).

You’ll sometimes see a pthread_exit in main used instead of explicit pthread_join calls, the intent being that exiting main in this way will allow other threads to continue running. In fact, the linux man page states this explicitly:

To allow other threads to continue execution, the main thread should terminate by calling pthread_exit() rather than exit(3).

But I don’t know if this is expected behavior on all platforms, and I’ve always stuck to using pthread_join.

pthread_join requires the pthread_t for the target thread, so your code will need to change a bit since you need to create both threads before calling pthread_join to wait for them both. So you can’t call it in startThread. You’ll need to return a pthread_t, or pass a pointer to a pthread_t to your startThread function.

Leave a Comment