线程资源释放

本文详细阐述了线程资源未正确释放可能导致的内存浪费、空间耗尽和程序卡死等问题,并提供了三种释放线程资源的方法:初始化线程时设置属性为可分离的、使用pthread_join与线程创建互斥、使用pthread_detach。通过实施这些方法,可以有效避免线程资源未释放带来的潜在风险。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

线程资源不释放结果会是怎么样?

代码如下:

[fy@localhost without_join]$ less main.c 
#include <stdlib.h>
#include <pthread.h>
#include <stdio.h>
#include <sched.h>
#include <errno.h>
void *consumer(void *p)
{
        static a = 0;
        a++;
        printf("thread id %u ,total thread  %d\n", (unsigned)pthread_self(), a);
        pthread_exit(NULL);
}
int main(int argc, char *argv[])
{
        pthread_t  t1, t2, t3;
        int ret;
        while(1)
        { 
                ret = pthread_create(&t1, NULL, consumer, NULL);
                if(ret != 0)
                {
                        printf("create failed,%d\n", ret);
                        exit(1);
                }
        };      
        sleep(1);
        return 0;
}    

部分运行结果:

thread id 71572368 ,total thread  287
thread id 61082512 ,total thread  288
thread id 50592656 ,total thread  289
thread id 40102800 ,total thread  290
thread id 29612944 ,total thread  291
thread id 19123088 ,total thread  292
thread id 3097111440 ,total thread  293
thread id 3107601296 ,total thread  294
thread id 3118091152 ,total thread  295
thread id 3128581008 ,total thread  296
thread id 3139070864 ,total thread  297
thread id 3149560720 ,total thread  298
thread id 3160050576 ,total thread  299
thread id 3170540432 ,total thread  300
create failed,11
[fy@localhost without_join]$ 

释放线程资源的形式有以下几种

1.初始化线程时,设置属性为可分离的

pthread_t thread;

pthread_attr_t attr;

pthread_attr_init(&attr);

pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);

pthread_create(&thread,&attr,fun,arg);

2.使用pthread_join(pthread_t thread , void **value);与1互斥

3.使用pthread_detach(pthread_self());

线程资源不释放造成内存资源浪费,产生溢出,空间耗尽,程序卡死。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值