线程创建与退出
前言: 多线程程序中,特别是频繁申请,释放线程的情况下,就要注意线程的关闭,最好使用线程池。
一,线程退出方式 (1) 执行完成后隐式退出;
(2) 由线程本身显示调用pthread_exit 函数退出;
pthread_exit (void * retval) ;
(3) 被其他线程用pthread_cance函数终止:
pthread_cance (pthread_t thread) ;
二,线程状态 pthread 线程有两种状态,joinable(非分离)状态和detachable(分离)状态,默认为joinable。 joinable:当线程函数自己返回退出或pthread_exit时都不会释放线程所用资源,包括栈,线程描述符等(有人说有8k多,未经验证)。 detachable:线程结束时会自动释放资源。
Linux man page said: When a joinable thread terminates, its memory resources (thread descriptor and stack) are not deallocated until another thread performs pthread_join on it. Therefore, pthread_join must be called once for each joinable thread created to avoid memory leaks.
因此,joinable 线程执行完后不使用pthread_join的话就会造成内存泄漏。
解决办法: 1.// 创建线程前设置 PTHREAD_CREATE_DETACHED 属性 pthread_attr_t attr; pthread_t thread; pthread_attr_init (&attr); pthread_attr_setdetachstat(&attr, PTHREAD_CREATE_DETACHED); pthread_create (&thread, &attr, &thread_function, NULL); pthread_attr_destroy (&attr);
2.当线程为joinable时,使用pthread_join来获取线程返回值,并释放资源。
3.当线程为joinable时,也可在线程中调用 pthread_detach(pthread_self());来分离自己。
三,参考文件 1,http://blog.csdn.net/bbs598598/article/details/7536853
- 分享
- 举报

-
浏览量:324次2019-12-05 16:50:26
-
浏览量:532次2019-11-30 12:03:18
-
浏览量:262次2020-02-26 10:09:04
-
浏览量:500次2020-02-29 12:04:47
-
浏览量:363次2018-05-26 16:08:31
-
浏览量:680次2017-12-16 17:23:30
-
浏览量:536次2018-11-30 12:43:18
-
浏览量:271次2023-10-09 18:56:58
-
浏览量:314次2018-01-20 11:43:49
-
浏览量:618次2020-07-24 17:13:30
-
浏览量:889次2020-07-29 14:50:28
-
浏览量:867次2018-09-08 16:03:33
-
浏览量:397次2019-01-14 23:45:06
-
浏览量:484次2020-07-30 09:28:30
-
浏览量:1665次2017-11-23 17:10:36
-
浏览量:422次2020-04-08 10:32:05
-
浏览量:425次2020-08-07 16:57:28
-
浏览量:1090次2017-11-22 11:47:47
-
浏览量:388次2017-12-25 22:17:13
-
广告/SPAM
-
恶意灌水
-
违规内容
-
文不对题
-
重复发帖
big_anana







举报类型
- 内容涉黄/赌/毒
- 内容侵权/抄袭
- 政治相关
- 涉嫌广告
- 侮辱谩骂
- 其他
详细说明