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.
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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…