linux 线程内存调整,linux创建线程内存回收

有三种方法可以回收线程内存

1.设置线程属性

pthread_attr_t p_pth_attr;

if  (0 != pthread_attr_init(&p_pth_attr))

{

perror("pthread_attr_init");

return -1;

}

if  (0 != pthread_attr_setdetachstate(&p_pth_attr, PTHREAD_CREATE_DETACHED))

{//此处设置成分离线程内存,一旦线程结束,立刻回收内存

perror("pthread_attr_setdetachstate");

return -1;

}

记住

p_pth_attr 也要析构,否则也会内存泄漏pthread_attr_destroy(&p_pth_attr );

2.在创建线程后调用pthread_join ()

3.使用pthread_detach()

void *ThreadFunc()

{

static int count = 1;

printf ("Create thread %d/n", count);

pthread_detach (pthread_self());

count++;

}

创建一个线程默认的状态是joinable, 如果一个线程结束运行但没有被join,则它的状态类似于进程中的Zombie Process,即还有一部分资源没有被回收(退出状态码),所以创建线程者应该调用pthread_join来等待线程运行结束,并可得到线程的退出代码,回收其资源(类似于wait,waitpid)

但是调用pthread_join(pthread_id)后,如果该线程没有运行结束,调用者会被阻塞,在有些情况下我们并不希望如此,比如在Web服务器中当主线程为每个新来的链接创建一个子线程进行处理的时候,主线程并不希望因为调用pthread_join而阻塞(因为还要继续处理之后到来的链接),这时可以在子线程中加入代码

pthread_detach(pthread_self())

或者父线程调用

pthread_detach(thread_id)(非阻塞,可立即返回)

这将该子线程的状态设置为detached,则该线程运行结束后会自动释放所有资源。

The pthread_detach () function indicates that system resources for the specified thread should be reclaimed when the thread ends. If the thread is already ended, resources are reclaimed immediately. This routine does not cause the thread to end. After pthread_detach () has been issued, it is not valid to try to pthread_join() with the target thread.

Eventually, you should call pthread_join () or pthread_detach () for every thread that is created joinable (with a detachstate of PTHREAD_CREATE_JOINABLE ) so that the system can reclaim all resources associated with the thread. Failure to join to or detach joinable threads will result in memory and other resource leaks until the process ends.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值