线程属性

细调pthread线程属性



基本概念:

pthread接口允许我们通过设置每个对象关联的不同属性来细调线程和同步对象的行为。


一、线程属性的初始化与反初始化

PTHREAD_ATTR_INIT(3)       Linux Programmer's Manual      PTHREAD_ATTR_INIT(3)

NAME
       pthread_attr_init, pthread_attr_destroy - initialize and destroy thread
       attributes object

SYNOPSIS
       #include <pthread.h>

       int pthread_attr_init(pthread_attr_t *attr);
       int pthread_attr_destroy(pthread_attr_t *attr);

       Compile and link with -pthread.
两个函数的返回值:若成功,返回0;否则,返回错误编号


二、图12-3同时给出了各个操作系统平台对每个线程属性的支持情况


三、关于线程栈

对于进程来说,虚地址空间的大小是固定的。因为进程中只有一个栈,所以它的大小通常不是问题。但对于线程来说,同样大小的虚地址空间必须被所有的线程栈共享。如果应用程序使用了许多线程,以致这些线程栈的累计大小超过了可用的虚地址空间,就需要减少默认的线程栈大小。另一方面,如果线程调用的函数分配了大量的自动变量,或者调用的函数涉及许多很深的栈帧(stack frame),那么需要的栈大小可能要比默认的大。


查看与设置栈大小:

PTHREAD_ATTR_SETSTACKSIZE(3Linux Programmer's ManuPTHREAD_ATTR_SETSTACKSIZE(3)

NAME
       pthread_attr_setstacksize,  pthread_attr_getstacksize  -  set/get stack
       size attribute in thread attributes object

SYNOPSIS
       #include <pthread.h>

       int pthread_attr_setstacksize(pthread_attr_t *attr, size_t stacksize);
       int pthread_attr_getstacksize(pthread_attr_t *attr, size_t *stacksize);

       Compile and link with -pthread.
两个函数的返回值:若成功,返回0;否则,返回错误编号

例子:

#include <pthread.h>
#include <stdio.h>

int main()
{
    pthread_attr_t attr;
    size_t stacksize;

    // get
    pthread_attr_init(&attr);
    pthread_attr_getstacksize(&attr, &stacksize);
    printf("thread stack size is %d kbyte\n", (int)stacksize/1024);

    // set size double
    stacksize *= 2;
    pthread_attr_setstacksize(&attr, stacksize);
    pthread_attr_getstacksize(&attr, &stacksize);
    printf("thread stack size is %d kbyte\n", (int)stacksize/1024);

    return 0;
}

运行结果,与ulimit对比,gcc pthread_stack.c -pthread:



四、关于线程分离

参考文章:linux分离线程


参考:《unix环境高级编程》·第三版

End;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值