简体   繁体   中英

Allocated memory for a thread in C++

Is it possible to fetch memory usage of a thread in windows programmed by C++? (I know that this is possible for processes with GetProcessMemoryInfo API.)

There isn't such a thing because although a thread has some semi-private memory (Thread Local Storage), the bulk of the memory allocated during a thread's run time is part of the process memory space.

A solution to your problem is to override the various allocation functions (eg malloc ) and have each malloc register the allocation using the current thread ID. You'll also need an API to query the allocation DB on how much was allocated.

Memory allocation from the shared heap is thread agnostic.

Unless you use specific heaps per thread or some other mechanism of accounting the OS has no way of knowing which thread is using what memory since more than one thread may be using the same memory region. If you do decide to use separate heaps (say 1/thread) on windows using HeapCreate you can then use HeapWalk to enumerate all allocated blocks per heap and sum the total allocated memory per thread.

I do not see any windows API that would do it for you. As others have pointed out, heap usage is not specific to a thread and the only thing you can do is to track which thread allocated how much.However, if you are interested only in stack usage, which is specific to each thread then it is straight forward to implement a pair of functions that can be called from within the thread context that will tell you how much stack space is in use at that instant. For this you can save the address of an automatic variable in your thread entry function as the "stack top" into a global thread safe map for later look up (say void SaveCurrentThreadStackTop(void*);) using thread id as key. Then at the point of use you call an function (say size_t GetCurrentThreadStackUsage(void);) that declares another automatic variable and subtracts it from the "stack top" saved earlier for current thread id. The result may not be accurate to the byte but close enough.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM