UnitUnit1;Interfaceuseswinapi.windows, Winapi.messages, System.sysutils, System.variants, system.classes, Vcl.graphics, Vcl.Controls, Vcl.forms, Vcl.dialogs, Vcl.stdctrls, System. SYNCOBJS;typeTForm1=class(tform) Button1:tbutton; Button2:tbutton; Memo1:tmemo; Checkbox1:tcheckbox; procedureformcreate (Sender:tobject); procedureFormdestroy (Sender:tobject); procedureButton1Click (Sender:tobject); procedureButton2click (Sender:tobject); procedureCheckbox1click (Sender:tobject); Private Public {Public Declarations} End; Tmythread=class(TThread)protected procedureExecute;Override; End;varForm1:tform1; Aevent:tevent; Mythread:tmythread;Implementation{$R *.DFM}procedureLog (MSG:string);beginTthread.synchronize (Nil,procedure beginForm1.Memo1.Lines.Add (MSG); End);End;{Tmythread}procedureTmythread.execute;begin while notTerminated Do beginAevent.acquire; Log (Datetimetostr (now)); Tthread.sleep ( -); End; Log ('Exit');End;procedureTform1.button1click (sender:tobject);beginaevent.setevent;End;procedureTform1.button2click (sender:tobject);beginaevent.resetevent;End;procedureTform1.checkbox1click (sender:tobject);beginmythread.terminate;End;proceduretform1.formcreate (sender:tobject);beginmemo1.clear; Aevent:= Tevent.Create(Nil, False, False,"'); MyThread:= Tmythread.Create(False);End;procedureTform1.formdestroy (sender:tobject);begin if notMythread.finished Then begin //make sure the thread exits gracefullymythread.terminate; Aevent.setevent; Mythread.waitfor; End; Mythread.free; Aevent.free;End;End.
Aevent: = tevent. Create (');
The first false whether the thread can be executed one time. How true, equivalent to the Do while, if false, is equivalent to while.
The second false, which is equivalent to whether the thread can run directly, does not require setevent. If true, the thread must be called after SetEvent to run. That is, the thread is blocked when it is started.
When both are False, a function similar to Pulseoneevent can be implemented.
Tlightweightevent and tevent are basically the same, it's from. NET in the System.Threading.ManualResetEventSlim. For multicore, the shorter time interval is more efficient, so refer to MSDN.
Delphi Multi-Thread tevent and Tlightweightevent