pthread_attr_t 线程属性(二)

一.函数:
1.线程属性的初始化与销毁:
#include <pthread.h>
int pthread_attr_init(pthread_attr_t *attr);
int pthread_attr_destroy(pthread_attr_t *attr);
Both return: 0 if OK, error number on failure
2.设置线程属性–detackstate(分离状态):
#include <pthread.h>
int pthread_attr_getdetachstate(const pthread_attr_t *restrict attr, int *detachstate);
int pthread_attr_setdetachstate(pthread_attr_t *attr, int detachstate);
Both return: 0 if OK, error number on failure
detachstate有两个选项:PTHREAD_CREATE_DETACHED 分离状态启动线程
PTHREAD_CREATE_JOINABLE 正常状态启动线程
3.设置线程属性–stackaddr(线程栈的最低地址),stacksize(线程栈的大小):
#include <pthread.h>
int pthread_attr_getstack(const pthread_attr_t *restrict attr,
void **restrict stackaddr,
size_t *restrict stacksize);
int pthread_attr_setstack(const pthread_attr_t *attr,
void *stackaddr,
size_t *stacksize);
Both return: 0 if OK, error number on failure
4.设置线程属性–stacksize(线程栈的大小):
#include <pthread.h>
int pthread_attr_getstacksize(const pthread_attr_t *restrict attr,
size_t *restrict stacksize);
int pthread_attr_setstacksize(pthread_attr_t *attr,
size_t stacksize);
Both return: 0 if OK, error number on failure
5.设置线程属性–guardsize(线程栈末尾的警戒缓冲区大小)
#include <pthread.h>
int pthread_attr_getguardsize(const pthread_attr_t *restrict attr,
size_t *restrict guardsize);
int pthread_attr_setguardsize(pthread_attr_t *attr,
size_t guardsize);
Both return: 0 if OK, error number on failure
二.重点:

三.例子:
以分离状态创建线程

[cpp] view plaincopy

#include <stdio.h>  
#include <pthread.h>  
#include <string.h>  
  
void * thr_fn()  
{  
    printf("thread run\n");  
    pthread_exit((void *)0);  
}  
  
int main()  
{  
    pthread_t tid;  
    pthread_attr_t attr;  
    int ret;  
  
    ret = pthread_attr_init(&attr);  
    if(ret!=0)  
        printf("init attr error:%s\n",strerror(ret));  
    ret = pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);  
    if(ret==0)  
    {  
        ret = pthread_create(&tid,&attr,thr_fn,NULL);  
        if(ret!=0)  
            printf("create thread error:%s\n",strerror(ret));  
    }  
    pthread_attr_destroy(&attr);  
    sleep(1);  
    return 0;  
}  

运行:
root@ubuntu1:~/12# ./a.out
thread run

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值