Einzelnen Beitrag anzeigen

Benutzerbild von Sprint
Sprint

Registriert seit: 18. Aug 2004
Ort: Edewecht
712 Beiträge
 
Delphi 5 Professional
 
#5

Re: Threads und die Zählvariable

  Alt 2. Dez 2004, 20:36
Zitat von SiD:
Leider kennt der Compiler InterlockedIncrement() nicht in der untThread?????
Das ist eine WinAPI Funktion die in der Unit Windows deklariert ist.

Ein Beispiel wie das aussehen könnte:

Delphi-Quellcode:
unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    Label1: TLabel;
    Label2: TLabel;
    Label3: TLabel;
    Button1: TButton;
    Button2: TButton;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
  private
    { Private-Deklarationen }
    Thread1: TThread;
    Thread2: TThread;
    Thread3: TThread;
  public
    { Public-Deklarationen }
  end;

type
  TDownloadThread = class(TThread)
  private
    FLabel: TLabel;
    FInternalCounter: Integer;
    procedure UpdateLabel;
  protected
    procedure Execute; override;
  public
    constructor Create(ALabel: TLabel);
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

var
  DownloadCounter: Integer;

constructor TDownloadThread.Create(ALabel: TLabel);
begin
  inherited Create(True);
  FLabel := ALabel;
end;

procedure TDownloadThread.UpdateLabel;
begin
  FLabel.Caption := IntToStr(FInternalCounter);
end;

procedure TDownloadThread.Execute;
begin
  FInternalCounter := InterlockedIncrement(DownloadCounter);
  while (not Terminated) and (FInternalCounter <= 300) do
  begin
    Synchronize(UpdateLabel);
    Sleep(500);
    FInternalCounter := InterlockedIncrement(DownloadCounter);
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin

  Thread1 := TDownloadThread.Create(Label1);
  with Thread1 do
  begin
    FreeOnTerminate := True;
    Priority := tpIdle;
    Resume;
  end;

  Thread2 := TDownloadThread.Create(Label2);
  with Thread2 do
  begin
    FreeOnTerminate := True;
    Priority := tpIdle;
    Resume;
  end;

  Thread3 := TDownloadThread.Create(Label3);
  with Thread3 do
  begin
    FreeOnTerminate := True;
    Priority := tpIdle;
    Resume;
  end;

end;

procedure TForm1.Button2Click(Sender: TObject);
begin

  Thread1.Terminate;
  Thread2.Terminate;
  Thread3.Terminate;

end;

end.
Ciao, Sprint.

"I don't know what I am doing, but I am sure I am having fun!"
  Mit Zitat antworten Zitat