C++ – What’s the best way to discover why threads are being created in the C++ app and what they do

cdebuggingmultithreadingwindows

I am doing an audit of a C++ app running on Windows, compiled against multithreaded debug DLL. It has a lot of third party dependencies which can spawn threads. I need to track why each thread is there and how much stack space it is allocating.

What is a good way to trace back to the start of a thread's creation so I can see where it is spawned?

Update: I should point out I have the source code to the entire app outside of Microsoft dependencies. However, a lot of the threads have callstacks that exist exclusively inside of libraries that ship with the OS such as ntdll.dll and kernel32.dll.

Best Answer

You can use the Windows Performance Toolkit to view ThreadCreate events. On Vista on up, you can get the stacks for each thread create, so you can see which code is creating the thread.

Collect the trace with:

xperf -on base -stackwalk ThreadCreate 

Run your scenario, the write out the trace with:

xperf -stop -d mylog.etl

View the trace file with:

xperf mylog.etl

In the Trace menu option, set your symbol path appropriately and load symbols. You can use the Microsoft Symbol Server to get public symbols for the operating system.

Under "Process Lifetimes", right click and select "Thread Summary Table". You can add columns for creation stack and user stack size. Expand your process, you can see all threads that were created, the stack that created that thread, and the stack size.