>    TThread mystery since D6/D7  (Arno Garrels)

First, consult the very extensive TThread documentation in D7 Help 
and look at the demo.

Here's what I use since D7:

uses ..., SyncObjs, ...{in delphi7\source\rtl\common}

const
   ThreadTimeout = 600000; {ten minutes or whatever you prefer}

var
   AResult: TWaitResult;
   ThreadCounterGuard: TCriticalSection;
   ThreadEndEvent: TEvent;
   ThreadCounter: Integer;
   lpSystemInfo : _System_Info;

   GetSystemInfo(lpSystemInfo);
   NumberOfProcessors := lpSystemInfo.dwNumberOfProcessors;

   if (NumberOfProcessors > 1) then
   begin
     ThreadCounterGuard := TCriticalSection.Create;
     ThreadEndEvent := TEvent.Create(nil, True, False, '');
...

    ThreadEndEvent.ResetEvent;
    ThreadCounter := NumberOfProcessors;

     AThread1: TAThread;
     AThread2: TAThread;
    etc.

{make as many threads as maximum anticipated number of processors, 
currently 4 with two dual core Pentiums or two Xeons with 
hyperthreading enabled in the bios, or use routines from the FastCode 
project to get processor details. A single processor with 
hyperthreading turned on looks like two in WinXP}

   AThread1 := TAThread.Create(....);
   AThread2 := TAThread.Create(....);
   etc.

     {threads start doing something as soon as they are created}
     {they may contain:}

   TAThread = class(TThread)
   private
...
     functions
     procedures

   protected
     procedure Execute; override;
   public
     constructor Create(...);
     destructor Destroy; override;
   end;

constructor TAThread.Create(...);
   inherited Create(False);
   FreeOnTerminate := True;
   Priority := tpHighest; {or whatever you prefer}
...
end;

destructor TAThread.Destroy;
begin
   inherited Destroy;
end;

...

procedure TAThread.Execute;
begin

{do the work here}

   ThreadCounterGuard.Acquire;
   Dec(ThreadCounter);
   if (ThreadCounter = 0) then
     ThreadEndEvent.SetEvent;
   ThreadCounterGuard.Release;

end;

     {and importantly, just in case a thread stalls for whatever reason}

     AResult := ThreadEndEvent.WaitFor(ThreadTimeout); {or some worst 
case time}

     if (Aresult <> wrSignaled) then
         ShowMessage('Thread Timeout on ' + IntToStr(ThreadCounter));

{before finally shutting things down with:}

     ThreadCounterGuard.Free;
     ThreadEndEvent.Free;

I hope that this helps.

Irwin Scollar 

_______________________________________________
Delphi mailing list -> [email protected]
http://www.elists.org/mailman/listinfo/delphi

Reply via email to