Mutha
Mutha

Reputation: 11

How to list threads in the same process?

I have this code that runs through all threads. I would like to get the threads only from my own process, without having to loop through all the threads running on the system.

var
  SnapProcHandle: THandle;
  NextProc      : Boolean;
  TThreadEntry  : TThreadEntry32;
begin
  SnapProcHandle := CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
  Result := (SnapProcHandle <> INVALID_HANDLE_VALUE);
  if Result then
  try
    TThreadEntry.dwSize := SizeOf(TThreadEntry);
    NextProc := Thread32First(SnapProcHandle, TThreadEntry);
    while NextProc do
    begin
      if TThreadEntry.th32OwnerProcessID = PID then
      begin
        Memo1.Lines.Add('Thread ID      '+IntToStr(TThreadEntry.th32ThreadID));
        Memo1.Lines.Add('base priority  '+inttostr(TThreadEntry.tpBasePri));
        Memo1.Lines.Add('delta priority '+inttostr(TThreadEntry.tpBasePri));
      end;
      NextProc := Thread32Next(SnapProcHandle, TThreadEntry);
    end;
  finally
    CloseHandle(SnapProcHandle);
  end;
end;

Upvotes: 0

Views: 1282

Answers (2)

You can do this with WMI (Windows MIcrosoft Instrumentation). Here there are an article that explain how to retrieve all threads running of one process. The article is in spanish, but you can use authomatic translation o view the code and download samples.

Using WMI you can obtain all information of a process using the class Win32_Process class. You can try execute in a console a coomand like this, to obtain information of this class.

WMIC Process where name="bds.exe" GET Name, description, ProcessId, ThreadCount, Handle

enter image description here

With this you can obtain information of process.

The second step if "How to retrieve the Threads associated a process". You can do this with the Win32_Thread class.

If you launch a query like this:

SELECT * FROM WIN32_THREAD WHERE ProcessHandle=10740

You get all the threads of the process 10740 (see ProcessId of the first query).

Regards.

Upvotes: 1

Remy Lebeau
Remy Lebeau

Reputation: 595412

You already know how to filter the threads for a specific process, because the code is already doing exactly that:

if TThreadEntry.th32OwnerProcessID = PID then

All you need is the PID for the calling process. Use GetCurrentProcessId() to get that value.

Unfortunately, CreateToolhelp32Snapshot() does not allow you to restrict the snapshot to a specific process when using TH32CS_SNAPTHREAD, the snapshot includes all threads in the system, so you need to filter them on their respective PIDs as you loop through them.

Upvotes: 2

Related Questions