线程的销毁 -- 分离属性

线程结束,缺少pthread_join 的话,资源并不会真正释放,设置线程 分离属性 ,则可不需要join 都可以释放资源。

实例:

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include < string.h>
#include <pthread.h>
pthread_t pid_new_job;  
CourseInfo NextCourseInfo;

#define ID_SIZE 48+1 

struct CourseInfo{
    
     char ID[ID_SIZE];
     int Last_Percent;
    CourseInfo()
    {
        memset(ID, 0, sizeof(ID));      
        Last_Percent =  0;
    }
};

void *thread_handleSpace( void *args)
{
    printf( " \n======= thread_handleSpace Begin =======\n ");
    CourseInfo *pCI = (CourseInfo*)args;
    printf( " \n======= thread_handleSpace End =======\n ");
    pthread_exit(NULL);
}

int main( void)
{
       strcpy(NextCourseInfo.ID , " 121 ");
    pthread_attr_t attr;
        
     int res ;
    res = pthread_attr_init(&attr); // 属性
     if(res !=  0)
    {
        printf( " exit 1 ");
         return - 1;
    }
    
    res = pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM); // 建立线程的争用范围(PTHREAD_SCOPE_SYSTEM 或 PTHREAD_SCOPE_PROCESS)。 使用 PTHREAD_SCOPE_SYSTEM 时,此线程将与系统中的所有线程进行竞争。使用 PTHREAD_SCOPE_PROCESS 时,此线程将与进程中的其他线程进行竞争
    res += pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
     if(res !=  0)
    {
        printf( " exit 2 ");
         return - 1;
    }
    
    res = pthread_create(&pid_new_job, NULL, thread_handleSpace, ( void *) &NextCourseInfo);//全局的NextCourseInfo,为了防止销毁了该变量(此前在这的sleep 可以不用)
         //     pthread_join(pid_new_job,NULL); // 无需此句了。
    pthread_attr_destroy(&attr);
     return  0;
}

 

测试:用文字界面登录你的linux , 在调用前中后 用free 命令 打印前后的内存对比吧。可以在线程中吃掉more memory, 以更明显的看出结果。

 
dengwei@dengwei-laptop:/media/dengwei/blog$ free
             total       used       free     shared    buffers     cached
Mem:        984680     847920     136760          0      53784     351384
-/+ buffers/cache:     442752     541928
Swap:      1354744          0    1354744
dengwei@dengwei-laptop:/media/dengwei/blog$ ./CI &
.... 

dengwei@dengwei-laptop:/media/dengwei/blog$ free

             total       used       free     shared    buffers     cached
Mem:        984680     848536     136144          0      53800     351436
-/+ buffers/cache:     443300     541380
Swap:      1354744          0    1354744
[1]+  Done                    ./CI
dengwei@dengwei-laptop:/media/dengwei/blog$ free
             total       used       free     shared    buffers     cached
Mem:        984680     848612     136068          0      53808     351468
-/+ buffers/cache:     443336     541344

Swap:      1354744          0    1354744 

 

for more about attribute of thread: 

http://blog.sina.com.cn/s/blog_693301190100vvlf.html 

转载于:https://www.cnblogs.com/no7dw/archive/2012/02/23/2364109.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值