본문 바로가기

Delphi/끄적이기

procedure를 Thread로 호출하기

var

.., System.Classes;

type

IMyThread = interface function Handle: THandle; procedure Start; end; TMyThread = class(TInterfacedObject, IMyThread) private Thread : TThread; FHandle : THandle; public function Handle: THandle; procedure Start; constructor Create(AProc: TProc; isStart: Boolean = True); destructor Destroy; override; end;

{ TAutoThread } constructor TMyThread.Create(AProc: TProc; isStart: Boolean = True); begin Thread := TThread.CreateAnonymousThread(AProc); Thread.FreeOnTerminate := False; FHandle := Thread.Handle; if isStart then Thread.Start; end; destructor TMyThread.Destroy; begin if Assigned(Thread) then begin Thread.Terminate; Thread.WaitFor; FreeAndNil(Thread); end; inherited; end; function TMyThread.Handle: THandle; begin Result := Self.FHandle; end; procedure TMyThread.Start; begin Thread.Start; end;

procedure RunThreadProc(AProc: TProc);

var MyThread : IMyThread; begin

//단일 프로시저일 경우 MyThread := TMyThread.Create(AProc);

WaitForSingleObject(MyThread.Handle, ATimeOut); end; procedure RunMultiThreadProc(arrProc: array of TProc); var I : Integer;

nThreadCount : Integer; arrHandle : array of THandle; arrThread : array of IMyThread; begin

//다수의 프로시저를 동시에 호출해야할 경우

nThreadCount := High(arrProc) + 1; SetLength(arrHandle, nThreadCount); SetLength(arrThread, nThreadCount); for I := 0 to nThreadCount - 1 do begin arrThread[I] := TMyThread.Create(arrProc[I]); arrHandle[I] := arrThread[I].Handle; end; WaitForMultipleObjects(nThreadCount, @arrHandle, True, INFINITE); end;


반응형