Search code examples
c++windowspdh

Counting number of threads on windows server; counter path


There was a similar thread about this here, and I tried to implement it myself. i.e. Trying to get the number of threads running in the server using c++ library.

May I know exactly what COUNTER_PATH is? (e.g. "\Process(*_)\Thread Count" in the given link)? What does it mean to make a string with that and the pid number?

The following is what I have wrote so far without really understanding anything:

#include <windows.h>
#include <pdh.h> //and suppose there're other libraries as necessary...

CONST PWSTR COUNTER_PATH = L"\Process(*)\Thread Count";

int returnNumThreads()
{
    HQUERY hQuery = NULL;
    HCOUNTER hCounter;
    DWORD counterType;
    PDH_FMT_COUNTERVALUE counterValue;
    PWSTR Paths = NULL;
    PDH_STATUS pdhStatus = PdhOpenQuery(NULL, 0, &hQuery);

    pdhStatus = PdhAddCounter(hQuery, COUNTER_PATH, 0, &hCounter);
    pdhStatus = PdhCollectQueryData(hQuery);
    pdhStatus = PdhGetFormattedCounterValue(hCounter,
                    PDH_FMT_LONG,
                    &counterType,
                    &counterValue);
    return counterValue.longValue;
}

// **Here, I removed all the error checking codes such as 
// "if (pdhStatus != ERROR_SUCCESS){...}" for better readability

**Also, the solution given in the link above says to expand the wildcard path, but when I checked the PdhAddCounter page, it said: "If the counter path contains a wildcard character, all counter names matching the wildcard character are added to the query," so I wasn't sure if expansion is really needed.

I've been looking at various examples, but I'm not still sure if I'm creating the query correctly or still what that COUNTER_PATH is. Can anybody give me an explanation?


Solution

  • PdhAddCounter adds named counters to an open query. L"\Process(*)\Thread Count" is such a name. It's considered a "path" name as its syntax is hierarchical (parts separated by \), similar to file paths.

    The wildcard means that you want to add the thread counters for Process(Foo), Process(Bar), etc to get the total number of threads for all processes together. (If you're running two copie of foo.exe, the second is \Process(Foo#1)