I want to count native threads of the current Windows process via C/C++. I see there’s a related question with a .NET answer, but I can’t use that solution. I suspect that there may be a solution via PdhOpenQuery/PdhCollectQueryData but I haven’t explored that direction yet, and I’m hoping there’s an easier approach.
UPDATE: I should have said that my current implementation uses CreateToolhelp32Snapshot/Thread32First/Thread32Next and that’s what I’m trying to replace. That implementation is heavy-handed and causes 20,000 page faults on every invocation in my process. Maybe I’m just using it wrong?
Update2: The solution that worked best for me was to make a string like “\Process(_)\Thread Count” with the PID of the process I was interested in. Then I called PdhExpandWildCardPath() to expand the “” wildcard. Then I invoked PdhOpenQuery(), PdhAddCounter() and PdhCollectQueryData() to initialize. Thereafter, I called PdhCollectQueryData() and PdhGetFormattedCounterValue() to get my values periodically.
EDIT the second: Your text says "current process". If that is really the case, you could implement a small DLL whose DllMain maintains an active thread counter using
InterlockedDecrement(onDLL_THREAD_DETACH) andInterlockedIncrement(onDLL_THREAD_ATTACH).You would have to make sure your process loads up this DLL early on so the thread count starts at 1 for our main thread. Then your thread count is always up to date and quickly accessible via the
Interlocked*APIs.EDIT: For improved performance, you could access the PerfMon counters for your process and get the thread count for a given process in one shot. There is VB code here that you could model off of.
You could also use WMI to enumerate threads by process but this is hardly an easy programming model.
PerfMon will be the fastest.
ORIGINAL:
Raymond Chen has exact instructions for this here. Just need to filter by process ID matching your own (obtained via GetCurrentProcessId) in the condition before the
printf.