Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux: How to measure memory usage for a thread within process?

I want to measure memory usage for each thread within process. Is it possible? I'm trying to figure out which thread leaks memory.

Edit 1. The pmap for leaking process shows ~600 allocation by [ anon ]

...
63b00000    772K rw---    [ anon ]
63bc1000    252K -----    [ anon ]
63c00000    772K rw---    [ anon ]
63cc1000    252K -----    [ anon ]
63d00000    772K rw---    [ anon ]
...

Advice on what to do next?

Edit 2. Only virtual memory is leaking e.g. physical memory usage is stable.

like image 731
user1111666 Avatar asked Feb 18 '23 13:02

user1111666


2 Answers

No this isn't possible, because memory isn't attached to a thread but to the process. There is no link between a thread and some part of the memory.

What you seem to need is a profiler, which would point to the allocation points. One of them (didn't use it in the last decade) is Rational Purify.

like image 121
Denys Séguret Avatar answered Feb 21 '23 02:02

Denys Séguret


You generally can't identify the memory usage of a thread because memory ownership can freely move between threads. The kernel mapping tables will show you the usage of the process as a whole, i.e. the memory allocated for all threads.

Thread programming is hard. Unless you really need to freely share pointers and memory between threads - which is a fairly nasty code smell - it will probably be easier to debug if you rework your program as a flock of processes that communicate over IPC, which will also force you to consider which state needs to be shared. As a bonus, if the leaky process turns out to be a relatively short-lived one, the memory is returned to the system on exit() without you having to locate and patch the leak.

like image 45
pndc Avatar answered Feb 21 '23 04:02

pndc