Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
877 views
in Technique[技术] by (71.8m points)

linux - How to set pthread max stack size

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...