码迷,mamicode.com
首页 > 其他好文 > 详细

pthread_exit() in main()

时间:2014-11-21 14:23:22      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:linux   pthread   

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

  1. pthread_detach(pthread_self());
  2. 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‘).

- See full post at: http://bo-yang.github.io/2014/11/20/pthread_exit-in-main/#sthash.wisYChrz.dpuf

pthread_exit() in main()

标签:linux   pthread   

原文地址:http://blog.csdn.net/bonny95/article/details/41348327

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!