If you use multiple threads in Delphi for variable access, security issues may occur. For local variables and internal variables of objects, each thread object will be copied, so it will not interfere with each other. But what if global variables are accessed?
The value of the global variable cannot be determined. Let's take a look at the column.
Unit threadcopy; interfaceuses winapi. windows, winapi. messages, system. sysutils, system. variants, system. classes, VCL. graphics, VCL. controls, VCL. forms, VCL. dialogs, VCL. stdctrls; Type tform1 = Class (tform) btn1: tbutton; edt1: tedit; Procedure btn1click (Sender: tobject); Private {private Declarations} public {public declarations} end; var form1: tform1; implementation {$ R *. DFM} threadvar globalstr: string; Type ttlsthread = Class (tthread) Private fnewstr: string; protected procedure execute; override; Public constructor create (const anewstr: string); end; procedure setglobalstr (STR: string); begin if STR = ''then MessageBox (0, pchar (globalstr), 'this STR is .. ', mb_ OK) else globalstr: = STR; end; {ttlsthread} constructor ttlsthread. create (const anewstr: string); begin fnewstr: = anewstr; inherited create (false); end; Procedure ttlsthread. execute; begin freeonterminate: = true; setglobalstr (fnewstr); setglobalstr (''); end; Procedure tform1.btn1click (Sender: tobject); begin setglobalstr ('hello '); setglobalstr (''); ttlsthread. create ('dilbret'); sleep (100); setglobalstr (''); end.
Global Variables
What are the benefits of using threadvar in globalstr? If it is defined as threadvar, when the thread accesses globalstr, instead of using globalstr, it uses the copy of globalstr, so it does not affect access by other threads. You can try to run the aboveCode.