多线程使用基础篇(二) - pthread_create() pthread_attr_init() pthread_attr_setdetachstate()

1、 pthread_create(3)

#include <pthread.h>
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,\
                   void *(*start_routine) (void *), void *arg); 
参数:attr:用于线程两程属性的选择:joinable state和detached state
 其它功能、参数、返回值见:多线程使用基础篇(一)

2、pthread_attr_init(3)

#include <pthread.h>
 int pthread_attr_init(pthread_attr_t *attr);

功能:初始化线程属性
参数:
attr:线程属性
返回值:
成功:0 ;
失败:非 0 的错误号。

3、pthread_attr_setdetachstate(3)

#include <pthread.h>
int pthread_attr_setdetachstate(pthread_attr_t *attr, \
                                 int detachstate);

功能:设置attr属性
参数:
attr:线程属性
detachstate(将attr变量设置成以下两个宏之一):
PTHREAD_CREATE_DETACHED
PTHREAD_CREATE_JOINABLE
返回值 :
成功:0 ;
失败:非 0的错误号。

代码举例:

#include <stdio.h>
#include <pthread.h>
void *pth_detach_func(void *arg){//线程属性采用detached state调用这个函数 
    printf("pth_detach_func : %s\n",(char *)arg);
    return NULL;
}
void *pth_func(void *arg){//线程属性采用joinable state调用这个函数
    printf("pth_func : %s\n",(char *)arg);
    return NULL;
}
int main(void){
    pthread_t aptid,ptid;     //定义两个线程号
    pthread_attr_t attr_ptid;//定义线程属性变量
    pthread_attr_init(&attr_ptid);//初始华线程变量
    char test_buf[100] = "pthread detach learn .....";
    char buf[100] = "pthread  learn 2 .....";
    //设置线程属性attr_ptid使用的状态为detach
    pthread_attr_setdetachstate(&attr_ptid,PTHREAD_CREATE_DETACHED);
    //创建线程aptid,设置线程属性为attr_ptid,即线程aptid运行结束后,
    //自动回收资本线程资源,不需要使用pthread_join回收。
    pthread_create(&aptid,&attr_ptid,pth_detach_func,\
                     (void *)test_buf);
    //创建线程ptid,使用默认线程属性。
    pthread_create(&ptid,NULL,pth_func,(void *)buf);
    printf("pth_detach_func call  join return alue:%d\n",\
            pthread_join(aptid,NULL));
    printf("pth_func call join return value:%d\n",\
            pthread_join(ptid,NULL));
    return 0;
    }

运行结果:

pthread$gcc pdetach.c -lpthread
pthread$./a.out 
pth_detach_func : pthread detach learn .....
pth_detach_func call  join return value:22
pth_func : pthread  learn 2 .....
pth_func call join return value:0

由上述结果可以看出:当创建线程时,设置了线程属性为detached state时,线程运行完毕后自动回收了资源;调用pthread_join函数回收该线程资源,将得到一个错误代码。
如果创建线程时没有设置线程属性(NULL),将使用默认属性,由pthread_join函数等待线程结束,回收对应线程资源。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值