线程属性

    xiaoxiao2025-04-01  8

    基本概念:

    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;

    转载请注明原文地址: https://ju.6miu.com/read-1297601.html
    最新回复(0)