On the basis of the previous examples, the new problems are explored.
If we want several threads (3 examples) to execute sequentially, we can use a critical section, a signal, a mutex, and other means;
But the first example below what the synchronization tool is useless, but also to achieve the purpose; To do this, let the previous thread start the next thread before it ends.
The second example uses the mutex object to match the WaitForSingleObject function, and achieves similar purposes.
Effect graphs (two examples of similar effects, but the second example of the implementation of the order is not good guarantee):
code file for the first example:
Unit Unit1
Interface
uses
Windows, Messages, sysutils, variants, Classes, Graphics, Controls, Forms ,
Dialogs, Stdctrls, Extctrls;
Type
TForm1 = Class (Tform)
Paintbox1:tpaintbox;
Paintbox2:tpaintbox;
Paintbox3:tpaintbox;
Button1:tbutton;
Procedure Button1Click (sender:tobject);
Procedure Formdestroy (sender:tobject);
End;
Var
Form1:tform1
Implementation
{$R *.DFM}
Const
colors:array[0..2] of TColor = (clred, clgree n, Clblue);
var
harr:array[0..2] of Thandle
panitarr:array[0..2] of Tpaintbox;
function Threadfun (p:pointer): Int Eger stdcall;
var
I,n,x1,y1,x2,y2:integer;
Threadid:dword;
Begin
N: = Integer (P);
Panitarr[n]. Color: = Colors[n];
for I: = 0 does with Panitarr[n] do
begin
X1: = Random (Width); Y1: = Random (Height);
x2: = Random (Wid TH); Y2: = Random (Height);
Canvas.lock;
Canvas.ellipse (X1,Y1,X2,Y2);
Canvas.unlock;
Sleep (2);
End;
{If a new thread does not exceed 3 before the end of the previous thread, continue to build}
Inc (n),
if n < 3 then harr[n]: = CreateThread (nil, 0, @ThreadFun, PTR (n), 0, ThreadID);
Result: = 0;
End;
Procedure Tform1.button1click (sender:tobject);
var
id:dword
Begin
Panitarr[0: = PaintBox1
Panitarr[1]: = PaintBox2;
Panitarr[2]: = PaintBox3 ;
{Start with only one thread and pass in the 0 parameter as identity}
Harr[0]: = CreateThread (nil, 0, @ThreadFun, Ptr (0), 0, ID);
End;
Procedure TFo Rm1. Formdestroy (Sender:tobject);
var
i:integer
Begin
For I: = 0 to Length (HARR)-1 does CloseHandle (harr[i);
End;
End.
Form file:
object Form1: TForm1
Left = 0
Top = 0
Caption = 'Form1'
ClientHeight = 156
ClientWidth = 321
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'Tahoma'
Font.Style = []
OldCreateOrder = False
OnDestroy = FormDestroy
PixelsPerInch = 96
TextHeight = 13
object PaintBox1: TPaintBox
Left = 8
Top = 8
Width = 97
Height = 113
end
object PaintBox2: TPaintBox
Left = 111
Top = 8
Width = 98
Height = 113
end
object PaintBox3: TPaintBox
Left = 215
Top = 8
Width = 98
Height = 113
end
object Button1: TButton
Left = 238
Top = 126
Width = 75
Height = 25
Caption = 'Button1'
TabOrder = 0
OnClick = Button1Click
end
end