§How should I return from one pthread

1
2
3
4
5
6
7
void *thread_function(void* arg)
{
// body of my thread function

// pthread_exit(NULL);
// return NULL;
}

The pthread_exit function from pthread library exits the calling thread as its name implies. If one’s lazy, using return works as well. Quoted from the above link:

Performing a return from the start function of any thread other than the main thread results in an implicit call to pthread_exit(), using the function’s return value as the thread’s exit status.

§How about the main thread?

main thread is a bit special, which is the one runs main function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int main(int argc, char **argv)
{
// body of main function


// 1. the process exits; all running threads are killed.
// return 0;

// 2. the main thread exits, but the process will continue until the last thread exits
// pthread_exit(0);

// 3. wait for child-tread, then the process exits
// pthread_join(child, NULL);
// return 0;
}

Calling return in the main thread would call exit(3), which will terminate the whole process, meaning all the threads are killed. If we would like to wait for all the children threads, we need to call pthread_join explicitly, or call pthread_exit.

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