多线程开发学习笔记(1)

pthread_join()和pthread_detach(thread_self())

 

linux 线程有两种状态 joinable 和 unjoinable;

 

当线程处在joinable状态,则线程自己退出或用pthread_exit()退出都不会释放自己占有的堆栈和线程描述符(大概有8k左右),这是另外一种形式的内存泄露。

 

当线程处在unjoinable状态时,这些资源则会在线程退出时自动释放。

 

我们传统的用 pthread_create(pthread_t  thread, const pthread_attr_t* restrict_attr, void*(*start_rtn)(void),

void restrict_arg); 创建线程 默认的状态时joinable, 故要加上pthread_join.

 

要线程自己退出或pthread_exit退出时自己释放,大概有三种方法。

 

(一)用pthread_join()

pthread_t  tid = 0;

pthread_create(&tid, NULL, thread_func, NULL);

pthread_join(tid, NULL);

 

void* thread_func(void)

{

    //do something

}

 

(二)用pthread_detach()

pthread_t tid = 0;

pthread_create(&tid, NULL, thread_func, NULL);

 

void* thread_func(void)

{

    pthread_detach(pthread_self());

    //do something

}

 

(三)用pthread_attr_setdetachstate()

pthread_t tid = 0;

pthread_attr_t attr;

pthread_attr_init(&attr);

pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);

pthread_create(&tid, &attr, thread_func, NULL);

void* thread_func(void)

{

    //do something

}

三种用法没有好坏,仁者见仁智者见智。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值