When reading this article , You can also refer to :Delphi Thread class in TThread Implement multithreading programming ( event 、 A critical region 、Synchronize、WaitFor……)

But first, let me say RTL and VCL

RTL(Run-Time library), Runtime library , Include System、SysUtils、Math Three units , Functions and languages provided 、 compiler 、 Operating system and process

RTL Provide classes that inherit from TObject and RTL Inner class

VCL(Visual Component Library), Visual component library , Include Graphics、classes、Controls And other units related to classes and components

VCL Not thread safe

because VCL Not thread safe , So for VCL Can only be accessed in the main thread . This will mean : All code that needs to deal with users can only be executed in the environment of the main thread . This is an obvious deficiency in its structure , And the need seems to be limited to the surface , But it actually has some advantages

One of the main considerations in developing multithreaded projects is to use resources synchronously , Don't conflict , Actually, I want to Delphi Of VCL A component is also a resource , however VCL Not thread safe , You can't let other threads use , It can only be used through the main thread

1. A possible application scenario

For example, in the development of graphical interface projects , Need to connect to database , You can use this strategy : Use mainline to draw components to graphical interface , The process of connecting to the database is implemented in the sub thread .

At this time, we can ensure that even if there is a problem when connecting to the database , The child thread may try to connect all the time , But because Threads are not related to each other , Each executes its own logic code , So it doesn't affect the main thread drawing component , So the form doesn't get stuck

But you may have to read the data in the database in the child thread to display the data , This is the time , because VCL Not thread safe , So you can't allow the main thread ( Draw components ) And child threads ( Want to get the data from the database “ Write ” To the interface ) Operate components at the same time

So possible solutions ( see 3.Synchronize() Method ) Namely Use Synchronize() Method to call the child thread and want to transfer the data “ writes ” Interface method , This ensures that the method is actually executed in the main thread ( Although it's a subthread method , But by Synchronize() Method can implement the method of the sub thread to be executed in the main thread ), This ensures that multiple threads will not use VCL Components

2. The benefits of a single threaded user interface

First , Only one thread can access the user interface , This reduces the complexity of programming .Win32 Every thread that creates a window is required to use GetMessage() Build your own message loop . As you think , Such a program would be very difficult to debug , Because there are so many sources of information

secondly , because VCL Just one thread to access it , The code used to synchronize threads can be omitted , This improves the performance of the application

3.Synchronize() Method

stay TThread One of the ways is Synchronize(), Through it, some methods of the sub thread can be executed in the main thread .Synchronize() The statement of

procedure Synchronize(Method: TThreadMethod);

Parameters Method The type is TThreadMethod( It's a parameterless process ), The declaration of the type is as follows

type
TThreadMethod = procedure of object;

Method Parameter is used to pass the method executed in the main thread . With TTestThread Object as an example , If you want to display the calculated results in an edit box . In the first TTestThread Add to edit control Text Property to modify , then , use Synchronize() To call this method

Name this method GiveAnswer(), Here's the code for the example , It contains the code to update the edit control of the main form

unit ThrdU;
interface
uses
Classes; type
TTestThread = class(TThread)
private
Answer: Integer;
protected
procedure GiveAnswer;
procedure Execute; override;
end; implementation
uses
SysUtils, Main; {TTestThread}
procedure TTestThread.GiveAnswer;
begin
MainForm.Edit1.Text := IntToStr(Answer);
end; procedure TTestThread.Execute;
var
I: Integer;
begin
FreeOnTerminate:= True;
for I:= 1 to 2000000 do
begin
if Terminated then Breadk;
Inc(Answer, Round(Abs(Sin(Sqrt(I))));
Synchronize(GiveAnswer);
end;
end;

Synchronize() The purpose of is to execute a method in the main thread .

When you first create a subordinate thread in a program ,VCL An implicit thread window will be created and maintained from the main thread environment . The only purpose of this window is to pass Synchronize() The method called is queued

Synchronize() By Method The method passed by the parameter is saved in TThread Of FMethod Field , then , Send a CM_EXECPROC news , And put the message lParam The parameter is set to self( Here is the value thread object ). When the window procedure of the thread window receives this message , It calls FMethod Field . Because the thread window is created in the main thread , The window procedure of the thread window will also be executed by the main thread . therefore ,FMethod Field is executed in the main thread

The figure below illustrates vividly Synchronize() The internal mechanism and principle of

4. Use messages to synchronize

Instead of TThread.Synchronize() Method . have access to API function SendMessage() or PostMessage() To send messages . For example, the following code is used to set the edit box text in one thread and in another thread

var
S: String;
begin
S:= 'hello from threadland';
SendMessage(SomeEdit.Handle, WM_SETTEXT, 0, Integer(PChar(S)));
end;

Delphi: And VCL Sync (Synchronize()、 Use messages to synchronize ) More articles about

  1. VCL Thread synchronization method Synchronize( Use messages to synchronize )

    When reading this article , You can also refer to :Delphi Thread class in TThread Implement multithreading programming ( event . A critical region .Synchronize.WaitFor……) But first, let me say RTL and VCL RTL(Run-Time library ...

  2. Delphi Of VCL Component library

    Visual Component Library Abbreviation ( Visual component library )VCL yes Visual Component Library Abbreviation , Visual component library , It is Delphi,C++Builder And so on programming language basic ...

  3. Netty The client sends the message and gets the result synchronously

    The client sends the message and gets the result synchronously , It's actually against Netty The design principle of , But sometimes if you have to , Then the following design is suggested : For example, our specific usage is as follows : NettyRequest request = new N ...

  4. ActiveMQ producer Sync / Send message asynchronously

    http://activemq.apache.org/async-sends.html producer There are two modes of sending messages, synchronous and asynchronous , It can be configured by code : ((ActiveMQConnection)co ...

  5. Delphi Implement the method of getting handle and sending message (FindWindow、FindWindowEx、EnumChildWindows、SendMessage)

    Delphi Implement the method of getting handle and sending message In this paper, we give an example to illustrate Delphi The way to get a handle and send a message , The specific usage is as follows : Find a handle to another window : handle := FindWindow(nil, ...

  6. Rsync Sync 、Rsync+Lsync Real time synchronization

    Rsync Sync .Rsync+Lsync Real time synchronization Original blog post http://www.cnblogs.com/elvi/p/7658049.html #!/bin/sh #Myde by Elven @ #c ...

  7. mongosync Sync 1,oplog Synchronization reads other sets synchronization

    Use mongosync Synchronous data     Be careful : The one below me mongodb Lower version (3.2.16), You can also use this tool to synchronize data . The tool does not support a higher version of mongodb 了 . Usage method : https://g ...

  8. Use BestSync Synchronize software with nut cloud

    Free users of nut cloud can enjoy every month's 1G Upload and 3G Download traffic , At the same time, it claims to be the only domestic support WebDAV Cloud . My work doesn't back up many documents , I happen to have BestSync Synchronization software can use . Decided to try BestSync Of and WebDA ...

  9. js in ajax Connect to server open The other two default arguments to the function get Request and default asynchrony (open Of post The way send Function with arguments )(post Request and get Request differentiation :get: fast 、 Simple post: Security , Large amount of , Don't cache )( The difference between server synchronization and asynchronous : Sync : The browser can't do anything else while waiting for the server to respond )(ajax and jquery Used together )

    js in ajax Connect to server open The other two default arguments to the function get Request and default asynchrony (open Of post The way send Function with arguments )(post Request and get Request differentiation :get: fast . Simple post: Security , Large amount of , Don't cache )( ...

Random recommendation

  1. iOS Development Xcode8 Problems and changes encountered in

      iOS Development Xcode8 Problems and changes encountered in There will always be a lot of holes when a new version is released , There will be a lot of changes . Fill in one by one ... One . Problems encountered 1. Permissions and related settings iOS10 Call system album under the system . Camera function , Or apple health ...

  2. service name and SID The difference between

    Database name (DB_NAME). Instance name (Instance_name). And operating system environment variables (ORACLE_SID)  stay ORACLE7.8 There is only the database name in the database (db_name) And database instance name (instan ...

  3. Polygon Table - Google Chrome

    Polygon table by Pedro Amaro Santos Lisboa, Portugal posted at http://forums.cgsociety.org/showthrea ...

  4. Self configured WAMP Environmental Science , Expand oracle function library (oci)

    My colleague received a task yesterday , Use php Handle oracle The content of the database , however php open oracle Expansion is not like mysql Just use it that way , It needs something next to open First step Need to oracle Officially download one install ...

  5. BZOJ 3230: Similar substring ( RMQ + The suffix array + Two points )

    Find out by dichotomy k Large string , And then make the suffix array , RMQ seek LCP, Time complexity O(NlogN+logN) -------------------------------------------------- ...

  6. css Tips for hiding text

    Some time ago , On the project , There's a problem . There's one in the background “ Register now ” The button , Need to click . But the problem is : Now the picture is the background picture , If the picture is in html On the page , We can use anchors to add links to images . This is the time , We ...

  7. 【SQL】SQL in on Conditions and where The difference between conditions

     # Preface When a database returns records by connecting two or more tables , Will generate a temporary table in the middle , Then the temporary table is returned to the user . In the use of left jion when ,on and where The conditions differ as follows : 1.on The condition is that when the temporary table is generated ...

  8. Ajax Request to pass array parameters

    var ids = []; var rows=$("#tt").datagrid("getSelections"); for(var i=0; i<row ...

  9. use SQL The command is created manually CDB

    1. Set the environment variable   $ export ORACLE_SID=ora12c  $ export ORACLE_HOME=/home/oracle/product/12.1.0/db1  $ export ...

  10. Computer storage unit KB,MB,GB,TB,PB,EB,ZB,YB What's behind ?

    About computer storage units KB,MB,GB,TB,PB,EB,ZB,YB What's behind ? We know Kb yes 1000 Of 1 Power , therefore MB Namely 1000 Of 2 Power (106) GB Namely 1000 Of 3 Power (109) TB Namely 10 ...