Stack Usage Measurement for a Multithreaded Linux Application

I am developing a multi-threaded application for the embedded Linux platform.

Currently, I am setting the stack size for each thread (via pthread_set_attr) to a fairly large default value. I would like to fine tune this value for each thread to a smaller one to reduce the memory usage of the application. I could go through a trial and error path of setting each thread stack size to gradually smaller values ​​until the program crashes, but the application uses ~ 15 threads each with completely different functionality / attributes, so the approach will be extremely time-consuming.

I would prefer to be able to directly measure the use of the thread stack. Are there any helpful people who can recommend this? (For example, I come from the vxWorks background and using the "ti" command from the vxWorks shell gives directly statistics on the use of the stack, as well as other useful information about the status of the task.)

thank

+3
source share
3 answers

I don't know any good tools, but as a last resort, you could include some code in your application in your code, as shown below:

__thread void* stack_start;
__thread long stack_max_size = 0L;

void check_stack_size() {
  // address of 'nowhere' approximates end of stack
  char nowhere;
  void* stack_end = (void*)&nowhere;
  // may want to double check stack grows downward on your platform
  long stack_size = (long)stack_start - (long)stack_end;
  // update max_stack_size for this thread
  if (stack_size > stack_max_size)
    stack_max_size = stack_size;
}

The check_stack_size () function should be called in some of the most deeply nested functions.

Then, as the last statement in the stream, you can output stack_max_size somewhere.

stack_start :

void thread_proc() {
  char nowhere;
  stack_start = (void*)&nowhere;
  // do stuff including calls to check_stack_size()
  // in deeply nested functions
  // output stack_max_size here
}
+3

: pthread_attr_getstackaddr, , . , , .

+2

, (native pthreads) Linux:

Valgrind

:

valgrind --tool=drd --show-stack-usage=yes PROG

Valgrind - , . CPU.

Stackusage

:

stackusage PROG

Stackusage - , , Linux, glibc. , , Valgrind/drd .

Full disclosure: I am the author of Stackusage.

+2
source

Source: https://habr.com/ru/post/1696830/


All Articles