免费注册 查看新帖 |

Chinaunix

广告
  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 3296 | 回复: 3
打印 上一主题 下一主题

pthread编程-线程退出后为什么不会释放资源 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-09-07 11:41 |只看该作者 |倒序浏览
本帖最后由 wdove 于 2012-05-09 16:19 编辑

线程函数里什么都不干,pthread_join后线程占用的空间还是不释放。各位老大指教

tmp$ gcc a.c -lpthread
tmp$ ./a.out &
main process
[1] 3817
开始没有进入进程时,只有2M内存
tmp$ ps aux|grep -i a.out
b17931    3817  0.0  0.0   1728   392 pts/2    S    11:37   0:00 ./a.out
b17931    3819  0.0  0.0   3068   788 pts/2    R+   11:37   0:00 grep -i a.out
tmp$ thread fn1
线程执行完后,pthread_join了,应该释放内存,但是居然一直占用10M
tmp$ ps aux|grep -i a.out
3817  0.0  0.0  10056   460 pts/2    S    11:37   0:00 ./a.out
3822  0.0  0.0   3068   788 pts/2    R+   11:37   0:00 grep -i a.out
tmp$

程序代码:

  1. #include <stdio.h>
  2. #include <pthread.h>

  3. void* fn1(void* arg)
  4. {
  5.     printf("thread fn1\n");
  6.     return NULL;
  7. }


  8. int main()
  9. {
  10.     pthread_t tid;
  11.     printf("main process\n");

  12.     sleep(20);

  13.     pthread_create(&tid, NULL, fn1, NULL);
  14.     pthread_join(tid, NULL);

  15.     sleep(500);

  16.     return 0;
  17. }
复制代码

论坛徽章:
0
2 [报告]
发表于 2009-09-07 14:02 |只看该作者

回复 #1 wdove 的帖子

你调用线程之后,不仅仅是运行了你线程函数里面的代码吧?
应该还有很多位线程运行提供服务的后台资源没有释放。

论坛徽章:
0
3 [报告]
发表于 2009-09-07 18:43 |只看该作者
#include <stdio.h>
#include <pthread.h>

void* fn1(void* arg)
{
    printf("thread fn1\n");
    pthread_exit(0);
}


int main()
{
    pthread_t tid;
    printf("main process\n");

    sleep(20);

    pthread_create(&tid, NULL, fn1, NULL);
    pthread_join(tid, NULL);

    sleep(500);

    return 0;
}

论坛徽章:
0
4 [报告]
发表于 2009-09-08 11:05 |只看该作者
找到了,是因为thread栈大小默认是8192K,所以增了8M,可以用pthread_attr_setstacksize()去设置栈大小。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP