Strange result in multithreading using Delphi XE -
i trying utilize multithreading in delphi xe. task next have create 4 threads. each thread draw colored circle in paintbox @ predefined area, illustration first thread draw reddish circles in first quoter of paintbox, sec thread draw yellowish circles in sec quoter, , on.
i have defined next class
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;
in main code following:
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); := 0 numberoftreads - 1 begin thrarr[i] := tcalcthread.create(i, paintbox1); hndarr[i] := thrarr[i].handle; end; waitformultipleobjects(numberoftreads, @hndarr, true, infinite); := 0 numberoftreads - 1 thrarr[i].free; end;
the thread create , execute methods defined following:
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; := start finish 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;
as result getting few circles in 3 areas same color, , lot of circles in 1 area (the same color). doing wrong?
multithreading delphi tthread
No comments:
Post a Comment