Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query the thread count of a process using the regular Windows C/C++ APIs

Tags:

c++

c

winapi

Is there a way to query the number of threads that are currently running for a specific process using the standard Windows C/C++ APIs?

I already prowled through the MSDN docs but the only thing that comes near is

BOOL WINAPI GetProcessHandleCount(
  __in     HANDLE hProcess,
  __inout  PDWORD pdwHandleCount
);

which queries the number of system handles currently in use by a given process, which will include thread handles, but will not be limited to them.

Any insights would be greatly appreciated.

Thanks in advance.

Bjoern

like image 619
Bjoern Avatar asked Sep 20 '10 08:09

Bjoern


People also ask

How do I count the number of threads in a process?

Just as every process has a directory created under its PID, every thread has a directory created under its thread ID. This is found in the /proc/<pid>/task directory. The total number of directories in the task directory is the number of threads created for a process.

How do I see threads in Process Explorer?

Select Processes and Threads on the View menu to open the Processes and Threads window. If this window is already open, it becomes active.


2 Answers

Just to be complete here is some sample code based on the code sample, which can be found under the link stated in the comments section of the accepted answer:

#if defined(_WIN32)

#include <windows.h>
#include <tlhelp32.h>

/**
Returns the thread count of the current process or -1 in case of failure.
*/
int GetCurrentThreadCount()
{
    // first determine the id of the current process
    DWORD const  id = GetCurrentProcessId();

    // then get a process list snapshot.
    HANDLE const  snapshot = CreateToolhelp32Snapshot( TH32CS_SNAPALL, 0 );
    
    // initialize the process entry structure.
    PROCESSENTRY32 entry = { 0 };
    entry.dwSize = sizeof( entry );

    // get the current process info.
    BOOL  ret = true;
    ret = Process32First( snapshot, &entry );
    while( ret && entry.th32ProcessID != id ) {
        ret = Process32Next( snapshot, &entry );
    }
    CloseHandle( snapshot );
    return ret 
        ?   entry.cntThreads
        :   -1;
}

#endif // _WIN32
like image 180
Bjoern Avatar answered Sep 20 '22 21:09

Bjoern


See this example: http://msdn.microsoft.com/en-us/library/ms686852(v=VS.85).aspx

like image 45
Ivo Avatar answered Sep 20 '22 21:09

Ivo