C函数之pthread_create()使用

用pthread_create方法创建的线程,默认是非detached的,也就是说当线程退出时它所占用的系统资源并没有完全真正的释放,也没有真正终止,就会出现内存泄漏

有个案子,按下button的时候我们就启动线程来播放一段声音,如果不停的按门铃发现一段时间之后就无法播放声音了,查下来发现创建线程失败error是cannot allocate memory。

 

以下提出有3种方法可以避免这个问题:

1. 在pthread_create创建线程时设置detached的属性,这样线程结束时会立即释放所用资源:

pthread_t thread;

pthread_attr_t attr;

pthread_attr_init( &attr );

pthread_attr_setdetachstate(&attr,1);

pthread_create(&thread, &attr, run, 0);

2. 在线程结束之前手动执行detached操作:

void run() {

pthread_detach(pthread_self());

}

int main(){

pthread_t thread;

pthread_create(&thread, NULL, run, 0);

//......

return 0;

}

3. 线程使用pthread_join,这样当pthread_join返回时,线程会释放资源:

int main(){

pthread_t thread;

pthread_create(&thread, NULL, run, 0);

//......

pthread_join(thread,NULL);

return 0;

}

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值