It is said that event (event object) is the most primitive synchronization method of multithreading, and I think it is the most flexible one.
The event object (the handle table) mainly contains two Boolean variables. You can see from its creation function:
FunctionCreateevent (lpeventattributes: psecurityattributes; {Security Settings}Bmanualreset: bool; {First Boolean}Binitialstate: bool; {second Boolean}Lpname: pwidechar {object name}): Thandle;Stdcall; {Response object handle}// When the first Boolean is false, the event object will be reset immediately after being controlled (paused). If it is true, it can be manually paused.// When the second Boolean is false, the object is set to paused after creation; true indicates the running state.
Compared with other similar products, it is flexible to "start running" (setevent) and "Pause running" (resetevent) at any time );
There is even a pulseevent function that can be controlled to suspend immediately after execution, which is very convenient.
VaR
F: integer; {use this variable to coordinate the output position of each thread}
Hevent: thandle; {event object handle}
FunctionMythreadfun (P: pointer): DWORD;Stdcall;
VaR
I, Y: integer;
Begin
INC (f );
Y: = 20* F;
ForI: = 0 To200000 Do
Begin
IfWaitforsingleobject (hevent, infinite) = wait_object_0Then
Begin
Form1.canvas. lock;
Form1.canvas. textout (20, Y, inttostr (I ));
Form1.canvas. Unlock;
End;
End;
Result: = 0;
End;
ProcedureTform1.button1click (Sender: tobject );
Begin
Repaint; F: = 0;
Closehandle (hevent); {if it has been created}
Hevent: = createevent (Nil, True, true,Nil);
End;
{Creation thread}
ProcedureTform1.button2click (Sender: tobject );
VaR
Threadid: DWORD;
Begin
Createthread (Nil, 0, @ Mythreadfun,Nil, 0, Threadid );
End;
{Pause}
ProcedureTform1.button3click (Sender: tobject );
Begin
Resetevent (hevent );
End;
{Start}
ProcedureTform1.button4click (Sender: tobject );
Begin
Setevent (hevent );
End;
{Execute an instant pause after startup}
ProcedureTform1.button5click (Sender: tobject );
Begin
Pulseevent (hevent );
End;
ProcedureTform1.formcreate (Sender: tobject );
Begin
Button1.caption: = 'create event Object';
Button2.caption: = 'create thread';
Button3.caption: = 'resetevent';
Button4.caption: = 'setevent';
Button5.caption: = 'pulseevent';
End;
ProcedureTform1.formdestroy (Sender: tobject );
Begin
Closehandle (hevent );
End;