Menu Home

linux多线程之pthread_detach

pthread_detach(pthread_self())

linux线程执行和windows不同,pthread有两种状态joinable状态和unjoinable状态,
如果线程是joinable状态,当线程函数自己返回退出时或pthread_exit时都不会释放线程所占用堆栈和线程描述符(总计8K多)。只有当你调用了pthread_join之后这些资源才会被释放。

若是unjoinable状态的线程,这些资源在线程函数退出时或pthread_exit时自动会被释放。
unjoinable属性可以在pthread_create时指定,或在线程创建后在线程中pthread_detach自己, 如:pthread_detach(pthread_self()),将状态改为unjoinable状态,确保资源的释放。或者将线程置为 joinable,然后适时调用pthread_join。(网络资料)

pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
pthread_create(pID, &attr, func,NULL);
pthread_attr_destroy(&attr);

在func函数中使用:

pthread_detach(pthread_self()); //分离thread,释放线程资源

2 replies

  1. My wife and i were really excited that Chris managed to carry out his studies by way of the ideas he obtained while using the web pages. It is now and again perplexing to simply find yourself offering guidance which often people today have been making money from. And now we do understand we now have the website owner to thank for that. The most important illustrations you’ve made, the simple site menu, the relationships you can give support to promote – it’s most remarkable, and it’s really aiding our son and us reason why that content is pleasurable, and that’s unbelievably mandatory. Thanks for the whole lot!

  2. Thank you for each of your work on this web site. My mother takes pleasure in making time for investigations and it is simple to grasp why. All of us learn all relating to the dynamic way you provide very helpful tactics via your web blog and as well improve response from website visitors on that subject so my princess is certainly starting to learn a whole lot. Enjoy the rest of the new year. You’re conducting a remarkable job.

Leave a Reply

Your email address will not be published.