Delphi thread global variable copy

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.