有没有一种方法可以使用标准的 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/