java thread detach,linux 多线程编程 pthread_create和pthread_detach

pthread_create()

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg);

第一个参数表示线程id, 第二个参数表示该线程的属性(?),

第三个参数表示该线程的启动函数,第四个参数表示传入参数

线程创建之后,如果应该使用pthread_join函数对这个线程进行回收的。

pthread_join

pthread_join函数使用阻塞的方式,使得使线程结束以回收资源。

当不希望阻塞时,可以使用:

pthread_detach(pthread_self())//使线程自己结束后自动回收资源

pthread_detach(tid)//希望tid的线程号结束后自动回收资源,这样不会产生僵死进程

示例代码

#include "apue.h"

void *thread_fun()

{

printf("new thread is running!\n");

sleep(2);

return (void *)0;

}

int main()

{

pthread_t tid;

int err;

err = pthread_create(&tid, NULL, thread_fun, NULL);

if(err != 0)

{

printf("create thread failed!\n");

return -1;

}

//pthread_join(tid, NULL);

pthread_detach(tid);

return 0;

}

喜欢 (0)or分享 (0)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值