想用三个线程(或更多)在一个memo中按顺序生成0--900的数字,大家看看下面代码为何不行?procedure tt.Execute;
var ii:integer;
begin
i:=0;
for ii:= 0 to 300 do
    begin
    EnterCriticalSection(Critical1);
    form1.memo1.Lines.Add(inttostr(i));
    inc(i);
    LeaveCriticalSection(Critical1);
    end;
end;有时显示到(比如16)却又开始从1开始计数....

解决方案 »

  1.   

    unit Unit3;interfaceuses
      Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
      Dialogs, StdCtrls;type
      TForm3 = class(TForm)
        ListBox1: TListBox;
        Button1: TButton;
        procedure Button1Click(Sender: TObject);
      private
        { Private declarations }
        I: Integer;
        function AddI(): Integer;
      public
        { Public declarations }
        constructor Create(AOwner: TComponent); override;
      end;var
      Form3: TForm3;implementation{$R *.dfm}type
      TMyFunc = function (): Integer of object;  TMyThread = class(TThread)
      private
        { private declarations }
        FEvent: TMyFunc;
      protected
        { protected declarations }
        procedure Execute; override;
        procedure DoMyFunc;
      public
        { public declarations }
        constructor Create(aEvent: TMyFunc); reintroduce;
      published
        { published declarations }
      end;function TForm3.AddI: Integer;
    begin
      Result := InterlockedIncrement(I);
      ListBox1.Items.Add(IntToStr(Result));
    end;procedure TForm3.Button1Click(Sender: TObject);
    var
      FThread1, FThread2, FThread3: TThread;
    begin
      FThread1 := TMyThread.Create(AddI);
      FThread2 := TMyThread.Create(AddI);
      FThread3 := TMyThread.Create(AddI);
      FThread1.Resume;       
      FThread2.Resume;
      FThread3.Resume;
    end;constructor TForm3.Create(AOwner: TComponent);
    begin
      inherited;
      I := 0;
    end;{ TMyThread }constructor TMyThread.Create(aEvent: TMyFunc);
    begin
      inherited Create(True);
      FEvent := aEvent;
      FreeOnTerminate := True;
    end;procedure TMyThread.DoMyFunc;
    begin
      if Assigned(FEvent) then
        FEvent();
    end;procedure TMyThread.Execute;
    var
      I: Integer;
    begin
      inherited;
      for I := 1 to 300 do
        Synchronize(DoMyFunc);
    end;end.
      

  2.   

    关键是这个:Synchronize的使用
      

  3.   

    那也不能确保是按顺序的 你知道 CPU 分配给谁啊?
      

  4.   

    to 楼上的:InterlockedIncrement这个就可以确保是顺序的,