|
1-1 Basic concepts of Multithreading
WIN 98/NT/2000/XP is a multitasking operating system, that is, a process can be divided into multiple threads,
Each thread occupies the CPU running time and resources in turn, or splits the CPU time into slices, and each slice is allocated to different threads.
In this way, each thread takes turns to "Suspend" and "wake up", because the time slice is very small, it gives people the feeling that it is running at the same time.
Multithreading brings the following benefits: (read by yourself)
1) avoid bottlenecks;
2) parallel operations;
3) improve efficiency;
In multithreading, priority management can give priority to important programs and improve the flexibility of task management.
On the other hand, in a multi-CPU system, different threads can be executed in different CPUs to achieve real consistency
Multi-task processing (WIN 98 is only simulated, while win/NT/2000 is a real multi-CPU operation at the same time ).
Two concepts of multithreading:
1) process: it is also called a task. A program loads memory and allocates resources, which is called a "process ". Note: Process local
It does not have to be executed. A process consists of the following parts:
A> A private address space, which is a set of virtual memory address spaces that can be used by processes;
B> code and data sources of the program;
C> system resources, such as operating system synchronization objects;
D> contains at least one thread (main thread );
2) thread: it is the execution unit of the program (the thread itself does not include the program code, but the process that actually owns the code)
Each process includes at least one thread, called the main thread. If a process has multiple threads, it can share the same thread.
And can be executed concurrently.
A thread is an execution unit of a process and the basic entity for the CPU time allocated by the operating system.
Components:
A> data structure;
B> CPU registers and stacks;
A thread in a process can run independently or control the running of another thread.
Note:
Multithreading cannot be abused. The book mentions several shortcomings of multithreading (self-reading ).
1-2 tthread object
Although Windows provides a lot of multi-threaded API functions
It is inconvenient and error-prone when used improperly. To solve this problem, Borland took the lead in introducing
Tthread object to solve the multi-threaded Design difficulties and simplify the processing of multi-threaded problems.
It should be noted that the tthread object does not have an instance, And it communicates with the interface, mainly relying on the main form (main VCL thread)
, Which is different from other objects.
I. Main Methods of tthread objects
Constructor thread:
Constructor create (createsuincluded: Boolean)
Where: createsuincluded = true is constructed but does not wake up
When the value is set to false, the system wakes up.
You can also use the following method
Inheried create (createsuincluded: Boolean)
Pending thread:
Suspend
(Increase the number of threads suspended by one)
Wake-up thread:
Resume
(Note: This attribute reduces the number of threads suspended by one. When the number of threads is 0, it is awakened. That is to say,
How many times does a thread need to be suspended and how many times does it need to be awakened. When the thread is suspended, the thread address pointer remains unchanged.
And then wake up from the pending place)
Destructor (clears the memory occupied by the thread ):
Destroy
Terminate the thread (which will be discussed later ):
Terminate
Ii. Simple Example of thread application:
The following example shows the application of the above method. We know that loop is one of the most dedicated running modes,
Now we want to create two thread objects to achieve Parallel Running of the loop. The specific method is as follows:
File --- New --- thread object
This automatically creates a thread unit in the main form (write the thread name in the dialog box), the default name
It is unit2. The second thread unit unit3.
Note that unit2 and unit3 have a given process:
Procedure object.exe cute;
Begin
End;
The program is automatically executed after the thread is awakened. You can also call other custom processes and functions.
The end of this process means the end of the thread program.
To construct a thread, define a construction process in the interface type area:
Type
Object = Class (tthread) // automatically provided, you can also directly change
Private
Protected
Procedure execute; override;
Public
Constructor create; // self-written
In the implementation area, write:
Constructor object. Create;
Begin
Inherited create (true );
End
The object is the name of the thread object. Therefore, we hope to call this constructor in the main form.
The create () parameter uses true to indicate that the constructed thread is suspended.
Note that if two constructor operations are performed in the same thread object, two independent threads are generated, not only
It is independent, and the local variables used by the thread are also independent. However, in order to simplify the problem, we have established two unique
Thread object, and the number of two cycles is different. During parallel operations, it is easy to determine that two different programs are running.
Assume that the names of the two thread objects are:
Mymath1
Mymath2
In unit1, the following statement should be made:
Implementation
<$ R *. DFM>
Uses unit2, unit3;
VaR thread1: mymath1;
Thread2: mymath2;
In this way, the corresponding thread method can be called through these two thread variables in the main thread.
The method for constructing a thread in the main thread area is as follows:
Thread1: = mymath1.create;
Thread2: = mymath2.create;
Pending:
Thread1.suspend;
Thread2.suspend;
Wake up:
Thread1.resume;
Thread2.resume;
Analysis structure:
Thread1.destroy;
Thread2.destroy;
It should be noted that because the thread unit needs to call the Edit Control (object) of form, two methods can be used:
1) define a tedit object in the thread unit, for example
Edit4: tedit;
Direct reference during Execute
However, in unit1, you must assign a value in the formcreate process:
Procedure tform1.formcreate (Sender: tobject );
Begin
Thread1.edit4: = edit1;
End;
In this way, associate edit4 In the first thread with edit1 in the form.
2) Declare the call to unti1 In the second thread, that is, add
Uses unit1;
In this way, you can directly call the control of the main form in this thread unit. For example, you can write in unit3:
Form1.edit2. Text: = inttostr (I)
After learning about these basic rules, you can write complicated multi-threaded programs.
Another note is that the thread unit generated by default has only one calling Unit:
Uses classes;
In this way, many functions and objects cannot be used in thread units. Therefore, when necessary
This routine copies most commonly used units for simplicity. This is not a recommended method because
In this way, too much garbage will be involved in the program, so what to copy and what to use is generally required.
Iii. Common API functions
When dealing with multithreading problems, Apis provided by windows are also frequently used. It should be noted that tthread
The internal encapsulation method of the object is mainly to call API functions. However, it is more comprehensive and safer. Direct call
API functions often encounter unexpected errors due to improper use. Therefore, I personally think that as long as tthread is used
If the object method can be solved, do not directly call the API function. The API function should only be used in the tthread object method.
It cannot be solved.
For example, when the tthread object method calls an API function internally, the Recommended default value is generally used, but more precise
You can directly use API functions.
In fact, the tthread object method has been recognized by most program designers. For example, the original VB does not have direct
The ability to process multiple threads, but VB.net claims that it has the ability to simply handle multiple threads.
The problem is explained.
The following describes several API functions. For clarity and convenience, it focuses on the description. You can describe the functions correctly.
Read the examples and manuals in the book:
Build thread:
Createthread (parameter 1, -- Security Attribute (generally = nil, default security attribute)
Parameter 2, -- thread stack ruler (generally = 0, same length as the main thread, and can be automatically changed as needed)
Parameter 3, -- point to the Function Name Pointer, @ function name. This parameter is very important and cannot be called successfully if it is incorrect.
Parameter 4, -- the parameter that the user needs to pass to the thread. It is a pointer to the structure and nil is used when no parameter is required.
Parameter 5) -- input some thread-related parameters, for example:
Create_suincluded creates a suspended thread;
0 is activated immediately after creation.
There are clear examples of this function application in the book. You can read it by yourself.
It is generally not recommended to use the createtheard function, but to use
Begintheard function, because in addition to creating a thread and an entry function, it also adds several protection measures,
For details, refer to the 10th page description in the book.
The two API functions corresponding to suspend and resume are:
Function suspendthread (hthread: thandle): DWORD;
Function resumethread (hthread: thandle): DWORD;
Among them, thandle is required to control the thread handle. The function call is successful, the number of hangs is returned, and the call is unsuccessful.
0 xffffffff is returned.
4. Termination and exit of a thread:
1) automatically Exit:
A thread exits from the execute () process, which means that the thread is terminated.
Exitthread () function to clear the stack occupied by the thread. If the freeonterminate attribute of the thread object is set
True, the thread object is automatically deleted and the resources occupied by the thread are released.
This is the easiest way to eliminate thread objects.
2) Controlled Exit:
The terminate attribute of a thread object can be used to control the exit of a thread by a process or another thread. Only
Call the terminate method of the thread and set the terminate attribute of the linear program object to true. In the thread
This constantly monitors the value of terminate. Once it is found that it is true, it exits. For example, during the execute () process, you can write as follows:
While not terminate do
Begin
........
End;
3) exited API functions:
The API function declaration for thread exit is as follows: Code
Function terminatethread (hthread: thandle; dwexitcode: DWORD );
However, this function will immediately terminate the Code, regardless of whether the program has
Try... finally
Mechanism, which may cause errors.
4) use the thread suspension method (suspend)
Use the suspend method of the suspended thread, followed by a free thread, you can also release the thread, for example:
Thread1.suspend; // pending
Thread2.free; // release
There are examples in the book.
5. thread priority:
In the case of multithreading, it is generally necessary to give the thread a proper priority based on the importance of the thread to execute the task, such
If the number of threads simultaneously requests the CPU time, the thread with a higher priority takes precedence.
In Windows, the thread priority is divided into 30 levels, while in Delphi, The tthread object is relatively simple
There are seven levels. That is, an enumeration type ttthreadpriority is declared in tthread:
Type
Ttthreadpriority (tpidle, tplowest, tplower, tpnormal, tphight, tphighest, tptimecrest)
The corresponding values are minimum (valid when the system is idle,-15), low (-2), low (-1), and normal (normal 0)
, High (1), relatively high (2), maximum (15 ).
The tpidle and tptimecrital are somewhat special. For details, please read the relevant content in the book.
To set the priority, you can use the priority attribute of the thread object:
Threadobject. Priority: = tthreadpriority (level );
Here is an example showing the priority of multithreading:
1-3 use multithreading in the database
1) Use the ADO Mode
Since the ADO Data Source Control of Delphi 6.0 has built-in multithreading capabilities
The thread does not need to do more work. Use two adotable controls to connect to two databases, and
Datasource control. You can contact the data help control to handle database problems in the front and back.
2) use the BDE mode and tseeion object
If you need to use the BDE mode, you need to consider the session issue when using the database with multiple threads. In a single thread,
A session is automatically generated when each data source is created. This is a private file about the database information of the data source.
However, when multiple threads are used, the tsession object must be managed in a unified manner. Therefore, a tsession object is provided in BDE.
The same databas data source object.
Databas data sources can accept databases from different data platforms.
Database 1 --- databas (2) ---- table (qurey) (3) --- datasource
|
|
| --------- Tsession (1)
|
|
Database 2 --- databas (2) ---- table (qurey) (3) --- datasource
Method:
1) tsession
Attribute: sessionname = Name (from)
Active = true (activated)
2) database (multiple databases are allowed)
Attribute: sessionname = tsession name
Dataname = Name (self-initiated, used as the table identifier)
Aliasname = database alias
Connected = true (activated)
3) table or qurey
Attribute: sessionname = tsession name (do not use the default value)
Databasename = if the previous name is set, the database will appear here
.
Tablename = table name
Active = true (activated)
In the future, for example, adding datasoure to the database is the same as other databases. In this way, we can construct two database management systems processed by the front and back ends.
1-4 multi-thread synchronization mechanism
The synchronization mechanism is actually an event-driven mechanism, which means that the thread is in the "Sleep" state at ordinary times unless a certain
Events.
For example, when a copy file is copied, the copy thread completes a program block and then wakes up the process thread to fill in a cell.
The necessity of studying the multi-thread synchronization mechanism is that if the same resource is called at the same time during multi-thread synchronization,
There may be problems. Generally, reading data will not be a problem. However, if you write data (global variables, databases ),
Conflicts or even deadlocks and competition.
1. Use the synchronize Method
This method is used to access resources managed by the VCL main thread. The application of this method is:
Step 1: Put the code for accessing the main window (or the main window control resource) into a method of the thread;
Step 2: Use the synchronize method in the execute method of the thread object.
Instance:
Procedure theater.exe cute;
Begin
Synchronize (update );
End;
Procedure theater. update;
Begin
.........
End;
Synchronize is used to synchronize the update of the thread method.
Ii. Use the look method of VCL class
Among the components provided by Delphi IDE, some objects provide the thread synchronization mechanism, and the working thread can
Directly use these controls, such as tfont, tpen, tbitmap, tmetafile, and ticon. In addition
The required control object is called TCanvas. A lock method is provided for thread synchronization. When a thread uses this control object
First, call the lock method of this object, then operate the control, and then call the unlock side
To release control of the inter-controller.
For example:
Canversobject. Look;
Try
Drawing
Finally
Canversobject. Unlock;
End;
<Use this protection mechanism to ensure that unlock is executed no matter whether there is any exception or not. Otherwise, a deadlock may occur.
When designing multiple threads, pay attention to the deadlock issue>
Iii. waitfor Method
You can call the waitfor method when a thread waits for the end of another thread. This method belongs to the waiting line.
The prototype of the waitfor method is as follows:
Function waitfor (const astring: string): string;
For example, in the preceding basic thread example, add
Thread1.resume;
Thread1.waitfor;
Thread2.resume;
All threads can run only after thread1 is completed, including the main thread. As expected,
Since thread1 calls the edit control of the main form, edie1 is not displayed during thread1 running.
This tells us that such Code cannot be part of the main thread.
When another thread ends and the other thread waits for access to the user interface, the program may be deadlocked.
This should be used with caution.
4. Use Windows APIs for synchronization
Windows API functions provide many synchronization technologies. The following is a brief introduction.
1) critical section
A basic problem encountered when using a thread is that multiple threads access the same object, for example, accessing the same
Files, DLL, and the same communication resources, especially database access. When multiple threads write data to the same database field
The result is uncertain.
The critical section is used to solve this problem. It can prevent other threads from accessing sensitive data.
When using dry data, initialize the data first. Declare a variable of the trtlcriticalsection type:
VaR
CS: trtlcriticalsection;
Initialization:
Initializecriticalsection (CS );
Exclusive
Entercriticalsection (CS );
Exclusive relief
Leavecriticalsection (CS );
The use of critical zones is a convenient and well-defined thread synchronization mechanism and is widely used.
Note that the critical section can only be used in one process. You must first mark the generation that uses the data as the operation in the critical section.
Before executing this part of the code, the computer must first check the global record and determine whether other threads are at critical
And check whether the critical section is related to the first critical section, that is, the same program may have
Then the computer determines the running policy.
The following simple example describes how to use the critical section:
Below
2) mutex object
3) semaphores |