C++关于线程栈尺寸实战

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chengqiuming/article/details/89057878

一 点睛

栈尺寸是线程的另外一个重要属性。这对于我们在线程函数中开设栈上的内存空间非常重要。局部变量、函数参数、返回地址等都存放在栈空间里,而动态分配的内存或全局变量都属于堆空间。注意在线程函数中开设局部变量(尤其是数组)不要超过默认栈尺寸大小。

二 获得线程默认栈尺寸大小和最小尺寸

#ifndef _GNU_SOURCE  
#define _GNU_SOURCE     /* To get pthread_getattr_np() declaration */  
#endif  
#include <pthread.h>  
#include <stdio.h>  
#include <stdlib.h>  
#include <unistd.h>  
#include <errno.h>  
#include <limits.h>
static void * thread_start(void *arg)  
{  
    int i,res;  
    size_t stack_size;
    pthread_attr_t gattr;  
    res = pthread_getattr_np(pthread_self(), &gattr);  
    if (res)  
        printf("pthread_getattr_np failed\n");  
    
    res = pthread_attr_getstacksize(&gattr, &stack_size);
    if (res)
        printf("pthread_getattr_np failed\n");
    
    printf("Default stack size is %u byte; minimum is %u byte\n", stack_size, PTHREAD_STACK_MIN);
     
    
     pthread_attr_destroy(&gattr);  
}  
      
int main(int argc, char *argv[])  
{  
    pthread_t thread_id;  
    int s;  
    s = pthread_create(&thread_id, NULL, &thread_start, NULL);  
    if (s != 0)  
    {
        printf("pthread_create failed\n");
        return 0;
    }
    pthread_join(thread_id, NULL); //等待子线程结束
}  

三 运行

[root@localhost test]# g++ -o test test.cpp -lpthread
[root@localhost test]# ./test
Default stack size is 8392704 byte; minimum is 16384 byte

猜你喜欢

转载自blog.csdn.net/chengqiuming/article/details/89057878