使用Delphi XE进行多线程处理的结果很奇怪

时间:2014-10-18 23:38:41

标签: multithreading delphi tthread

我正在尝试在Delphi XE中使用多线程。 我必须创建4个线程。每个线程在Paintbox中的预定义区域绘制彩色圆圈,例如,FIRST线程仅在Paintbox的第一个引号中绘制红色圆圈,SECOND线程仅在第二个引脚中绘制黄色圆圈,依此类推。

我定义了以下类

const
  NumberOfIterations = 100000;
  NumberOfTreads = 4;

TCalcThread = class(TThread)
private
  FIdx: Integer;
  FHits: Cardinal;
  V: array of Integer;
  xPaintBox1: TPaintBox;
protected
  procedure Execute; override;
public
  constructor Create(Idx: Integer; vPaintBox: TPaintBox);
  property Hits: Cardinal read FHits;
end;

在主要代码中,我执行以下操作:

procedure TForm11.Button1Click(Sender: TObject);
var
  thrarr: array[0..NumberOfTreads - 1] of TCalcThread;
  hndarr: array[0..NumberOfTreads - 1] of THandle;
  i, a, t: Integer;
  x, y: Integer;
begin
 caption := '';

 PaintBox1.Canvas.Brush.Color := clWhite;
 PaintBox1.Canvas.fillrect(PaintBox1.Canvas.ClipRect);

 for i := 0 to NumberOfTreads - 1 do
 begin
   thrarr[i] := TCalcThread.Create(i, PaintBox1);
   hndarr[i] := thrarr[i].Handle;
 end;

 WaitForMultipleObjects(NumberOfTreads, @hndarr, True, INFINITE);

 for i := 0 to NumberOfTreads - 1 do
   thrarr[i].Free;
end;

线程Create和Execute方法定义如下:

constructor TCalcThread.Create(Idx: Integer; vPaintBox: TPaintBox);
begin
  FIdx := Idx;
  FHits := 0;
  xPaintBox1 := vPaintBox;

  case FIdx of
    0: xPaintBox1.Canvas.Pen.Color := clRed;
    1: xPaintBox1.Canvas.Pen.Color := clYellow;
    2: xPaintBox1.Canvas.Pen.Color := clBlue;
    3: xPaintBox1.Canvas.Pen.Color := clMoneyGreen;
  end;

  xPaintBox1.Canvas.Brush.Color := xPaintBox1.Canvas.Pen.Color;
  inherited Create(False);
end;

procedure TCalcThread.Execute;
var
  i, start, finish: Integer;
  x, y: Integer;
begin
  start := (NumberOfIterations div NumberOfTreads) * FIdx;
  finish := start + (NumberOfIterations div NumberOfTreads) - 1;

  for i := start to finish do
  begin
    case FIdx of
    0: begin
         x := Random(200) + 1;
       end;
    1: begin
         x := Random(200) + 201;
       end;
    2: begin
         x := Random(200) + 401;
       end;
    3: begin
         x := Random(200) + 601;
       end;
    end;

    y := Random((xPaintBox1.height )) + 1;
    xPaintBox1.Canvas.Ellipse(X - 5, Y - 5, X + 5, Y + 5);
  end;
end;

因此,我在三个区域中获得了几个相同颜色的圆圈,并且在一个区域中有很多圆圈(相同的颜色)。我做错了什么?

0 个答案:

没有答案