It's fine to use pthread_exit in main. When pthread_exit is used, the main thread will stop executing and will remain in zombie(defunct) status until all other threads exit.
If you are using pthread_exit in main thread, cannot get return status of other threads and cannot do clean-up for other threads (could be done using pthread_join(3)). Also, it's better to detach threads(pthread_detach(3)) so that thread resources are automatically released on thread termination. The shared resources will not be released until all threads exit.
Its ok to use when not allocating resources in the main thread, clean-up is not needed. Below code shows using pthread_exit in the main thread. The second printf in main is not printed as main thread exits after calling pthread_exit. Ps output shows the defunct main thread.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <errno.h>
void *functionC(void *);
int main()
{
int rc;
pthread_t th;
if(rc = pthread_create(&th, NULL, &functionC, NULL))
{
printf("Thread creation failed, return code %d, errno %d", rc, errno);
}
printf("Main thread %lu: Sleeping for 20 seconds\n", pthread_self());
fflush(stdout);
sleep(20);
pthread_exit(NULL);
printf("Main thread %lu: This will not be printed as we already called pthread_exit\n", pthread_self());
exit(0);
}
void *functionC(void *)
{
printf("Thread %lu: Sleeping for 20 second\n", pthread_self());
sleep(20);
printf("Thread %lu: Came out of first and sleeping again\n", pthread_self());
sleep(20);
printf("CThread %lu: Came out of second sleep\n", pthread_self());
}
Output of the above code:
Main thread 140166909204288: Sleeping for 20 seconds
Thread 140166900684544: Sleeping for 20 second
Thread 140166900684544: Came out of first and sleeping again
CThread 140166900684544: Came out of second sleep
ps
output:
root@xxxx-VirtualBox:~/pthread_tst# ps -elfT |grep a.out
0 S root 9530 9530 9496 0 80 0 - 3722 hrtime 17:31 pts/1 00:00:00 ./a.out
1 S root 9530 9531 9496 0 80 0 - 3722 hrtime 17:31 pts/1 00:00:00 ./a.out
0 S root 9537 9537 2182 0 80 0 - 5384 pipe_w 17:31 pts/0 00:00:00 grep --color=auto a.out
root@xxxx-VirtualBox:~/pthread_tst# ps -elfT |grep a.out
0 Z root 9530 9530 9496 0 80 0 - 0 - 17:31 pts/1 00:00:00 [a.out] <defunct>
1 S root 9530 9531 9496 0 80 0 - 4258 hrtime 17:31 pts/1 00:00:00 ./a.out
0 S root 9539 9539 2182 0 80 0 - 5384 pipe_w 17:31 pts/0 00:00:00 grep --color=auto a.out`
Please check blog Tech Easy for more information on threads.