Is it possible to get a list of thread handles at any given time for the current process on win32 (in c++)?
Asked
Active
Viewed 1.2k times
2 Answers
11
You will find this article helpful. It gives the code for thread enumeration with the small nuances that come with using the tool help library.
For convenience (lifted from the article):
#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;
}

Mike Kwan
- 24,123
- 12
- 63
- 96
-
2Sadly, this gives you access to the ID of the threads, not the HANDLE as the requester asked. There does not appear to be any API to get the HANDLE from the ID. OpenThread on the ID returns an alternate HANDLE. – Jesse Chisholm Apr 02 '14 at 17:16
-
Just a heads up that the "toolhelp" API is **obnoxiously slow**... I would recommend calling `NtQuerySystemInformation` directly. – user541686 Mar 13 '18 at 05:46
4
- Win32: How do I enumerate all the threads belonging to a process in C++?
OpenThread
to convert identifiers to handles
-
2Just be aware that OpenThread returns an alternate HANDLE, not the original HANDLE. It is useful for everything except comparing to the original handle. And don't forget to CloseHandle when you are done with this alternate HANDLE. – Jesse Chisholm Apr 02 '14 at 17:18