Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set pthread max stack size

Tags:

linux

pthreads

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

like image 362
Ali Avatar asked Mar 15 '13 14:03

Ali


1 Answers

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.

like image 165
Gabriel Southern Avatar answered Sep 23 '22 00:09

Gabriel Southern