c++ - 如何使用常规 Windows C/C++ API 查询进程的线程数

标签 c++ c winapi

有没有一种方法可以使用标准的 Windows C/C++ API 查询特定进程当前正在运行的线程数?

我已经浏览了 MSDN 文档,但唯一接近的是

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

查询给定进程当前使用的系统句柄数,其中将包括线程句柄,但不限于此。

如有任何见解,我们将不胜感激。

提前致谢。

比约恩

最佳答案

为了完整起见,这里有一些基于代码示例的示例代码,可以在已接受答案的评论部分中所述的链接下找到:

#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

关于c++ - 如何使用常规 Windows C/C++ API 查询进程的线程数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3749668/

相关文章:

c++ - c 或 c++ 中是否有类似 subprocess.getoutput() 的函数或方法?

c - 查找 argv 中的参数数量?

c++ - 如何初始化句柄

c++ - URLDownloadToFile 总是返回 S_OK

c++ - 为什么编译器在调用 move 后选择复制 ctor

c++ - 我的堆栈实现 (C++) 代码中出现段错误,但无法理解原因

c++ - 在 C++ 中使用子列表实现树

c - 如何从 u-boot 内部为 Linux 内核选择不同的设备树

arrays - 堆上的动态多维数组

c++ - 使用 StringCbPrintf 格式化缓冲区