转载:https://www.jianshu.com/p/9aa67b22fec3
众所周知的pthread_create的函数原型如下:
#include <pthread.h>
int pthread_create(
pthread_t *restrict tidp, //新创建的线程ID指向的内存单元。
const pthread_attr_t *restrict attr, //线程属性,默认为NULL
void *(*start_rtn)(void *), //新创建的线程从start_rtn函数的地址开始运行
void *restrict arg //默认为NULL。若上述函数需要参数,将参数放入结构中并将地址作为arg传入。
);
其中设置堆栈大小就靠attr参数,测试代码如下:
#include <iostream>
#include <limits.h>
#include <pthread.h>
#include "error.h"
using namespace std;
int main(){
pthread_t thread;
size_t stacksize;
pthread_attr_t thread_attr;
int ret;
pthread_attr_init(&thread_attr);
int new_size = 20480;
ret = pthread_attr_getstacksize(&thread_attr,&stacksize);
if(ret != 0){
cout << "emError" << endl;
return -1;
}
cout << "stacksize=" << stacksize << endl;
cout << PTHREAD_STACK_MIN << endl;
ret = pthread_attr_setstacksize(&thread_attr,new_size);
if(ret != 0){
return -1;
}
ret = pthread_attr_getstacksize(&thread_attr,&stacksize);
if(ret != 0){
cout << "emError" << endl;
return -1;
}
cout << "after set stacksize=" << stacksize << endl;
ret = pthread_attr_destroy(&thread_attr);
if(ret != 0)
return -1;
return 0;
}
编译命令:
g++ main.cpp -o main -lpthread
运行结果如下:
[root@lh test]#./main
stacksize=8388608
16384
after set stacksize=20480
即:
系统的默认值:8388608
最小值:16384