Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a list with all the threads created by my application

I want to get a list with all the threads (except the main, GUI thread) from within my application in order to do some action(s) with them. (set priority, kill, pause etc.) How to do that?

like image 634
John Thomas Avatar asked Jan 13 '10 09:01

John Thomas


2 Answers

Another option is use the CreateToolhelp32Snapshot,Thread32First and Thread32Next functions.

See this very simple example (Tested in Delphi 7 and Windows 7).

program ListthreadsofProcess;

{$APPTYPE CONSOLE}

uses
  PsAPI,
  TlHelp32,
  Windows,
  SysUtils;

function GetTthreadsList(PID:Cardinal): Boolean;
var
  SnapProcHandle: THandle;
  NextProc      : Boolean;
  TThreadEntry  : TThreadEntry32;
begin
  SnapProcHandle := CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); //Takes a snapshot of the all threads
  Result := (SnapProcHandle <> INVALID_HANDLE_VALUE);
  if Result then
  try
    TThreadEntry.dwSize := SizeOf(TThreadEntry);
    NextProc := Thread32First(SnapProcHandle, TThreadEntry);//get the first Thread
    while NextProc do
    begin
      if TThreadEntry.th32OwnerProcessID = PID then //Check the owner Pid against the PID requested
      begin
        Writeln('Thread ID      '+inttohex(TThreadEntry.th32ThreadID,8));
        Writeln('base priority  '+inttostr(TThreadEntry.tpBasePri));
        Writeln('');
      end;

      NextProc := Thread32Next(SnapProcHandle, TThreadEntry);//get the Next Thread
    end;
  finally
    CloseHandle(SnapProcHandle);//Close the Handle
  end;
end;

begin
  { TODO -oUser -cConsole Main : Insert code here }
  GettthreadsList(GetCurrentProcessId); //get the PID of the current application
  //GettthreadsList(5928);
  Readln;
end.
like image 142
RRUZ Avatar answered Oct 27 '22 13:10

RRUZ


You can use my TProcessInfo class:

var
  CurrentProcess : TProcessItem;
  Thread : TThreadItem;
begin
  CurrentProcess := ProcessInfo1.RunningProcesses.FindByID(GetCurrentProcessId);
  for Thread in CurrentProcess.Threads do
    Memo1.Lines.Add(Thread.ToString);
end;
like image 31
vcldeveloper Avatar answered Oct 27 '22 13:10

vcldeveloper