Find all threads of a process given process id
Asked Answered
Y

2

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.

Yiddish answered 24/1, 2012 at 22:11 Comment(6)
Seems legit. See blogs.msdn.com/b/oldnewthing/archive/2006/02/23/537856.aspxDorr
Premature optimization, a machine doesn't usually have more than 1000 active threads. You could use TH32CS_SNAPALL to make it selective on th32ProcessID.Hindoo
@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.Cuesta
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.Hatbox
As far I know exist two another approaches using the Performance Data Helper (but you need to filter by the PID too ) or using the Win32_Thread 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.Straightout
Check these two out: Thread Walking, Enumerating Threads in WindowsTechnicolor
O
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.

Outermost answered 23/4, 2016 at 15:58 Comment(0)
F
0

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

Example code is here.

Furnishings answered 1/7, 2013 at 17:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.