It is said that event (incident object) is the most original synchronization method of multithreading, I think it is the most flexible one.
There are two Boolean variables in the Event object (the handle table), which can be seen clearly from its established function:
function CreateEvent(
lpEventAttributes: PSecurityAttributes; {安全设置}
bManualReset: BOOL; {第一个布尔}
bInitialState: BOOL; {第二个布尔}
lpName: PWideChar {对象名称}
): THandle; stdcall; {返回对象句柄}
//第一个布尔为 False 时, 事件对象控制一次后将立即重置(暂停); 为 True 时可手动暂停.
//第二个布尔为 False 时, 对象建立后控制为暂停状态; True 是可运行状态.
Compared with other peers, its flexibility is to "start Running" (SetEvent) and "Suspend operation" (ResetEvent) at any time;
There is even a pulseevent function that can control the execution of an immediate pause, which is very convenient.
This example effect chart:
code file: unit Unit1;
Interface
uses
Windows, Messages, sysutils, variants, Classes, Graphics, Controls, Forms,
Dialogs, Stdctrls;
type
TForm1 = Class (Tform)
Button1:tbutton;
Button2:tbutton;
Button3:tbutton;
Button4:tbutton;
Button5:tbutton;
procedure formcreate (sender:tobject);
procedure Formdestroy (sender:tobject);
procedure Button1Click (sender:tobject);
procedure Button2click (sender:tobject);
procedure Button3click (sender:tobject);
procedure Button4click (sender:tobject);
procedure Button5click (sender:tobject);
end;
var
Form1:tform1;
Implementation
{$R *.DFM}
var
F:integer; {Use this variable to coordinate the location of each thread output}
Hevent:thandle; {The handle of the event object}
function Mythreadfun (p:pointer): DWORD; stdcall;
var
I,y:integer;
begin
Inc. (f);
y: = * f;
For I: = 0 to 200000 do
begin
if WaitForSingleObject (hevent, INFINITE) = Wait_object_0 then
begin
Form1.Canvas.Lock;
Form1.Canvas.TextOut (y, IntToStr (i));
Form1.Canvas.Unlock;
end;
end;
Result: = 0;
end;
procedure Tform1.button1click (sender:tobject);
begin
Repaint; F: = 0;
CloseHandle (hevent); {If you have already created}
hevent: = CreateEvent (Nil, true, true, nil);
end;
{Create thread}
procedure Tform1.button2click (sender:tobject);
var
Threadid:dword;
begin
CreateThread (nil, 0, @MyThreadFun, nil, 0, ThreadID);
end;
{Pause}
procedure Tform1.button3click (sender:tobject);
begin
resetevent (hevent);
end;
{boot}
procedure Tform1.button4click (sender:tobject);
begin
SetEvent (hevent);
end;
{Perform an immediate pause after startup}
procedure Tform1.button5click (sender:tobject);
begin
pulseevent (hevent);
end;
procedure Tform1.formcreate (sender:tobject);
begin
button1.caption: = ' Create Event object ';
button2.caption: = ' Create thread ';
button3.caption: = ' resetevent ';
button4.caption: = ' setevent ';
button5.caption: = ' pulseevent ';
end;
procedure Tform1.formdestroy (sender:tobject);
begin
CloseHandle (hevent);
end;
end.