问题描述
API pthread_attr_setstacksize(pthread_attr_t *attr, size_t stacksize)
用于设置为创建的线程堆栈分配的最小堆栈大小(以字节为单位).
但是如何设置最大堆栈大小?
谢谢
The API pthread_attr_setstacksize(pthread_attr_t *attr, size_t stacksize)
is to set the minimum stack size (in bytes) allocated for the created thread stack.
But how to set the maximum stack size?
Thanks
推荐答案
如果使用pthread_attr_setstack
自己管理堆栈的内存分配,则可以精确设置堆栈大小.因此,在这种情况下,最小值与最大值相同.例如,下面的代码举例说明了程序尝试访问的内存大于分配给堆栈的内存的情况,结果程序出现段错误.
If you manage the allocation of memory for the stack yourself using pthread_attr_setstack
you can set the stack size exactly. So in that case the min is the same as the max. For example the code below illustrate a cases where the program tries to access more memory than is allocated for the stack and as a result the program segfaults.
#include <pthread.h>
#define PAGE_SIZE 4096
#define STK_SIZE (10 * PAGE_SIZE)
void *stack;
pthread_t thread;
pthread_attr_t attr;
void *dowork(void *arg)
{
int data[2*STK_SIZE];
int i = 0;
for(i = 0; i < 2*STK_SIZE; i++) {
data[i] = i;
}
}
int main(int argc, char **argv)
{
//pthread_attr_t *attr_ptr = &attr;
posix_memalign(&stack,PAGE_SIZE,STK_SIZE);
pthread_attr_init(&attr);
pthread_attr_setstack(&attr,&stack,STK_SIZE);
pthread_create(&thread,&attr,dowork,NULL);
pthread_exit(0);
}
如果您依赖自动分配的内存,则可以指定最小数量,但不能指定最大数量.但是,如果线程的堆栈使用量超过了您指定的数量,则程序可能会出现段错误.
If you rely on memory that is automatically allocated then you can specify a minimum amount but not a maximum. However, if the stack use of your thread exceeds the amount you specified then your program may segfault.
请注意,pthread_attr_setstacksize
的手册页显示:
Note that the man page for pthread_attr_setstacksize
says:
A thread's stack size is fixed at the time of thread creation. Only the main thread can dynamically grow its stack.
要查看该程序的示例,请尝试查看此链接
To see an example of this program try taking a look at this link
您可以尝试使用它们提供的代码段,看看是否没有分配足够的堆栈空间来使程序出现段错误.
You can experiment with the code segment that they provide and see that if you do not allocate enough stack space that it is possible to have your program segfault.
这篇关于如何设置pthread最大堆栈大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!