Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running threads count

I'm using delphi 2010, is there anyway to know running threads count of the project via delphi function or windows api?

like image 699
lmengyew Avatar asked Sep 28 '10 04:09

lmengyew


2 Answers

you can use the CreateToolhelp32Snapshot function with the TH32CS_SNAPTHREAD flag

see this code.

  uses
  PsAPI,
  TlHelp32,
  Windows,
  SysUtils;

    function GetTThreadsCount(PID:Cardinal): Integer;
    var
        SnapProcHandle: THandle;
        NextProc      : Boolean;
        TThreadEntry  : TThreadEntry32;
        Proceed       : Boolean;
    begin
        Result:=0;
        SnapProcHandle := CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); //Takes a snapshot of the all threads
        Proceed := (SnapProcHandle <> INVALID_HANDLE_VALUE);
        if Proceed 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
              Inc(Result);
              NextProc := Thread32Next(SnapProcHandle, TThreadEntry);//get the Next Thread
            end;
          finally
            CloseHandle(SnapProcHandle);//Close the Handle
          end;
    end;

And call in this way, using the GetCurrentProcessId function wich Retrieves the PID (process identifier) of your application.

Var
Num :integer;
begin
 Num:=GetTThreadsCount(GetCurrentProcessId);
end;
like image 147
RRUZ Avatar answered Oct 04 '22 17:10

RRUZ


See the sample code here that enumerates the threads of a process.

like image 22
dthorpe Avatar answered Oct 04 '22 17:10

dthorpe