6

I am trying to find if there is a better way to find all thread ids that belong to the current process. It looks like using CreateToolhelp32Snapshot with TH32CS_SNAPTHREAD and iterating over the threads to check if the thread's process id is equal to the current process id, is a solution but i want to avoid iterating all the running threads. I just want to iterate over the threads that belong to a given process. Please let me know if there is an API that is fast and simple. I need to do it in c++.

Thanks, Abhinay.

  • 1
    Seems legit. See http://blogs.msdn.com/b/oldnewthing/archive/2006/02/23/537856.aspx – Neil Jan 24 '12 at 22:17
  • 2
    Premature optimization, a machine doesn't usually have more than 1000 active threads. You could use TH32CS_SNAPALL to make it selective on *th32ProcessID*. – Hans Passant Jan 24 '12 at 22:22
  • @Hans: TH32CS_SNAPALL is described as "Includes all processes and threads in the system, plus the heaps and modules of the process specified in th32ProcessID" - so it will not help. – Alexey Kukanov Jan 24 '12 at 22:45
  • The .Net Process class has a Threads property, but it seems to grab a snapshot of all processes and threads from HKEY_PERFORMANCE_DATA, and then returns just the information for the current process. As you've noted, Toolhelp also grabs a snapshot of everything (and is less of a pain to use than performance data). psapi doesn't handle threads at all. I suspect you're out of luck. If you just need a thread list for your own process add a DLL whose DllMain will get notified when threads are created or destroyed. – arx Jan 24 '12 at 23:55
  • As far I know exist two another approaches using the [`Performance Data Helper`](http://msdn.microsoft.com/en-us/library/aa939698%28v=winembedded.5%29.aspx) (but you need to filter by the PID too ) or using the [`Win32_Thread`](http://msdn.microsoft.com/en-us/library/windows/desktop/aa394494%28v=vs.85%29.aspx) WMI Class filtering by the `ProcessHandle` property but the speed of the WMI in this case is not comparable to the WinAPI. So my advice is keep using the CreateToolhelp32Snapshot function. – RRUZ Jan 25 '12 at 00:24
  • Check these two out: [Thread Walking](http://msdn.microsoft.com/en-us/library/windows/desktop/ms686780(v=VS.85).aspx), [Enumerating Threads in Windows](http://stackoverflow.com/questions/1206878/enumerating-threads-in-windows) – Nikhil Aug 09 '12 at 15:27

2 Answers2

1

If the "current process" is one you've written, you can take advantage of the fact that DllMain functions get called any time a thread is added or terminated with reason codes of DLL_THREAD_ATTACH and DLL_THREAD_DETACH. It's simple to then keep your own list.

DougN
  • 4,407
  • 11
  • 56
  • 81
0

After using CreateToolhelp32Snapshot with TH32CS_SNAPPROCESS (0x00000002), you can get thread by using Thread32First function.

Example code is here.

Oyle Iste
  • 1
  • 2