且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何以编程方式获取Windows进程的线程数?

更新时间:2023-01-17 22:51:28

编辑第二个:您的文本显示为当前进程".如果真是这样,您可以实现一个小的DLL,其 DllMain 使用InterlockedDecrement(在DLL_THREAD_DETACH上)和InterlockedIncrement(在DLL_THREAD_ATTACH上)维护活动的线程计数器.

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 (on DLL_THREAD_DETACH) and InterlockedIncrement (on DLL_THREAD_ATTACH).

您必须确保您的进程尽早加载此DLL,以便主线程的线程计数从1开始.然后,您的线程数始终是最新的,并且可以通过Interlocked* API快速访问.

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.

为了提高性能,您可以一次访问PerfMon计数器来获取您的进程,并获得给定进程的线程计数.您可以在此处的VB代码中进行建模

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.

您还可以使用WMI按进程枚举线程,但这很难成为简单的编程模型.

You could also use WMI to enumerate threads by process but this is hardly an easy programming model.

PerfMon将是最快的.

PerfMon will be the fastest.

原始: Raymond Chen在此处上有确切的说明.只需按匹配您自己的进程ID进行过滤即可(通过

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.

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

int __cdecl main(int argc, char **argv)
{
 HANDLE h = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
 if (h != INVALID_HANDLE_VALUE) {
  THREADENTRY32 te;
  te.dwSize = sizeof(te);
  if (Thread32First(h, &te)) {
   do {
     if (te.dwSize >= FIELD_OFFSET(THREADENTRY32, th32OwnerProcessID) +
                      sizeof(te.th32OwnerProcessID)) {
       printf("Process 0x%04x Thread 0x%04x\n",
             te.th32OwnerProcessID, te.th32ThreadID);
     }
   te.dwSize = sizeof(te);
   } while (Thread32Next(h, &te));
  }
  CloseHandle(h);
 }
 return 0;
}