Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
976 views
in Technique[技术] by (71.8m points)

multithreading - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...