2

I am using C language and Linux as my programming platform.

In my app, I call pthread_create. Then I check the memory usage of my app using ps commandline tool and it adds 4 in the VSZ column.

But the problem is when the pthread_create function handler exits, the 4 that was added in the memory was not release. Then when the app call the pthread_create again, a 4 value was added again until it gets bigger.

I tried pthread_join and it seems the memory still getting bigger.

Thanks.

domlao
  • 15,663
  • 34
  • 95
  • 134
  • Duplicate of question asked just 3 hours ago by the same person. – Jens Gustedt Jun 23 '10 at 05:20
  • possible duplicate of [My app mem usage is growing using pthread.](http://stackoverflow.com/questions/3098080/my-app-mem-usage-is-growing-using-pthread) – Artelius Jun 24 '10 at 07:27

3 Answers3

9

ps is not the right tool to measure memory leaks. When you free memory, you are not guaranteed to decrease the process' vsize, both due to memory fragmentation and to avoid unnecessary system calls.

valgrind is a better tool to use.

Artelius
  • 48,337
  • 13
  • 89
  • 105
6

You should use either pthread_detach or pthread_join (but not both) on every pthread you create. pthread_join waits for the thread to finish; pthread_detach indicates that you don't intend to wait for it (hence the implementation is free to reclaim the storage associated with the thread when it terminates).

ditto what Artelius said about ps not being the right tool for diagnosing memory leaks.

David Gelhar
  • 27,873
  • 3
  • 67
  • 84
3

When you say
But the problem is when the pthread_create function handler exit

Are you doing an explicit pthread_exit(NULL) as part of the exiting after completion of the thread execution? Also, the pthread_exit() routine does not close any files that you might have opened in your thread; any files opened inside the thread will remain open even after the thread is terminated.

IntelliChick
  • 636
  • 4
  • 7
  • yeah, I call pthread_exit(NULL) at the end of the function. and my pthread function handler is just a simple printf in the screen. – domlao Jun 23 '10 at 03:13