Most threads call pthread_exit()
implicitly on return from the thread start routine.
Besides, pthread_exit()
also can be used to terminate the initial process thread in main()
,
leaving other threads to continue operation.
The process will go away automatically when
the last thread terminates. If you don’t care about the process exit status, or if is difficult to
know the created thread IDs(e.g. created by third party APIs), you can call
pthread_detach(pthread_self());
pthread_exit(NULL);
at the end of the main()
function.
However, you must be carefull when using pthread_exit()
in the main thread. Because after
calling pthread_exit()
and before the process really terminate, the process becomes “zombie”
- it still exists even though it is “dead”, just like a Unix/Linux process that’s terminated but hasn’t yet been “reaped” by a wait
operation.
The zombie process may retain most or all of
the system resources that
it used when running, so it is not a good idea to leave threads in this state for longer than necessary. And obviously, zombie process cannot save you resources! So also don’t try pthread_exit()
for
saving CPU and memory.
I also noticed a undocumented problem caused by pthread_exit()
- it may lead to failure
of open procfs(/proc/
) files! If one of your threads would open /proc/mounts
(currently
I only find this file will go wrong, and other procfs files like /proc/cpuinfo
or /proc/uptime
can
be successfully opened) during its life, and pthread_exit()
is called after creating
these threads in the main thread, you will meet the “Invalid argument” error because of functions like open("/proc/mounts",‘r‘)
.
原文地址:http://blog.csdn.net/bonny95/article/details/41348327