Simultaneous read and write global Data of Delphi multithreaded programming

Source: Internet
Author: User

began to study the most important multi-threaded read and write global data, combined with the example of the book, I modified to the following situation:


Unit tst_thread3u;

Interface

Uses

Windows, Messages, sysutils, variants, Classes, Graphics, Controls, Forms,dialogs, Stdctrls;

Type
TForm1 = Class (Tform)
Button1:tbutton;
Memo1:tmemo;
Button2:tbutton;
Button3:tbutton;
Procedure Button1Click (Sender:tobject);
Procedure Button2click (Sender:tobject);
Procedure Button3click (Sender:tobject);
Private
Procedure Threadsdone (Sender:tobject);
End

Tmythread=class (TThread)
Protected
Procedure Execute;override;
End

Var
Form1:tform1;

Implementation
{$R *.DFM}

Const
maxsize=128;
Var
nextnumber:integer=0;
doneflags:integer=0;
Globalarry:array[1..maxsize] of Integer;
Lock:byte; 1-Out of Sync 2-critical section 3-Mutex
Cs:trtlcriticalsection; Critical section
Hmutex:thandle; Mutually exclusive

function Getnextnumber:integer;
Begin
Result:=nextnumber;
Inc (Nextnumber);
End

Procedure Tmythread.execute;
Var
I:integer;
Begin
Freeonterminate:=true; Automatic free after termination
Onterminate:=form1.threadsdone;
If Lock<>3 then//non-mutex case
Begin
If lock=2 then EnterCriticalSection (CS); Establishing a critical section
For I: = 1 to MaxSize do
Begin
Globalarry[i]:=getnextnumber;
Sleep (5);
End
If lock=2 then LeaveCriticalSection (CS);//Leave the critical section
End else//-------Mutex
Begin
If WaitForSingleObject (hmutex,infinite) =wait_object_0 Then
Begin
For I: = 1 to MaxSize do
Begin
Globalarry[i]:=getnextnumber;
Sleep (5);
End
End
ReleaseMutex (Hmutex); Release
End
End

Procedure Tform1.threadsdone (Sender:tobject);
Var
I:integer;
Begin
INC (Doneflags);
If doneflags=2 Then
Begin
For I: = 1 to MaxSize do
MEMO1.LINES.ADD (IntToStr (globalarry[i));
If lock=2 then DeleteCriticalSection (CS); Delete a critical section
If lock=3 then CloseHandle (Hmutex); Close Mutex
End
End

Non-synchronous
Procedure Tform1.button1click (Sender:tobject);
Begin
Lock:=1;
Tmythread.create (False);
Tmythread.create (False);
End

Critical section
Procedure Tform1.button2click (Sender:tobject);
Begin
lock:=2;
InitializeCriticalSection (CS); Initialize critical section
Tmythread.create (False);
Tmythread.create (False);
End

Mutually exclusive
Procedure Tform1.button3click (Sender:tobject);
Begin
lock:=3; Mutually exclusive
Hmutex:=createmutex (0,false,nil);
Tmythread.create (False);
Tmythread.create (False);
End

End.

Without the help of a critical section and mutual exclusion, two threads are constantly outputting in Memo1, and the numbers are chaotic.


First, critical area

The so-called critical section is a piece of code that can be executed by only one thread at a time. If the code that initializes the array is placed in the critical section, the other thread will not be executed until the first thread has finished processing.

Steps to use a critical section:

1, first declare a global variable type of trtlcriticalsection;

2. Call the InitializeCriticalSection () procedure before the thread create () to initialize the function definition:

void WINAPI initializecriticalsection (lpcritical_section lpcriticalsection);

The type lpcriticalsection is the trtlcriticalsection of the Delphi package.

3, the need to put the thread into the critical section of the code before using the EnterCriticalSection (lpcriticalsection) process to start establishing a critical section. Use LeaveCriticalSection (lpcriticalsection) to mark the end of the critical section after the code is complete.

4, use DeleteCriticalSection (lpcriticalsection) to clear the critical area after the thread executes. This cleanup process must be placed after the thread executes, such as in the Formdesroy event. In the above example, if the process is placed in tmythread.create (False), an error is generated.

Second, mutual exclusion:

Mutexes are very similar to critical sections, except for the two key differences: First, mutexes can be used to synchronize threads across processes. Second, the mutex can be given a string name, and an additional handle to the existing mutex is created by referencing the name.

The most important difference between a critical section and an event object (such as a mutex) is performance. When there is no thread conflict, the critical section should use 10~15 time slices, and the event object will use 400~600 time slices because of the system kernel involved.

To use mutually exclusive steps:

1. Declaring a global variable of type Thandle or HWND is actually cardinal type. The HWND is the handle of window, which is used primarily for Windows handles, while Thandle is not limited.

2. Create a mutex with CreateMutex () before thread create (). The function is defined as:

HANDLE WINAPI CreateMutex (

Lpsecurity_attributes Lpmutexattributes,

BOOL Binitialowner,

LPCTSTR Lpname:pchar);

The lpsecurity_attributes parameter is a pointer to a tsecurityattributtes record. This parameter is set to nil, which represents the default security attribute for access control lists.

The Binitalowner parameter indicates whether the thread that created the mutex is to be the owner of this mutex object. When this parameter is False, indicates that the mutex object has no owner.

The lpname parameter specifies the name of the mutex object. Set to nil means no name, and if the parameter is not set to nil, the function searches for the existence of a mutex with the same name. If so, the function returns a handle to the mutex object with the same name. Otherwise, a new mutex object is created and its handle is returned.

The return value is a handle. When an error occurs, returns NULL, at which point the GetLastError function can be used to view the wrong information.

Using CreateMutex () can prevent multiple instances of a program from running, as in the following example:

Program ABC;

Uses forms,windows,...;

{$R *.res}

Var

Hmutex:hwnd;

Begin

Application.initialize;

Hmutex:=createmutex (Nil,false,pchar (application.title));

If Getlasterror<>error_already_exists Then

Begin

Project to run the boom

End

ReleaseMutex (Hmutex);

Application.Run;

End;

In this section of the routines, we just want to prevent threads from entering the synchronization code area, so the lpname parameter is set to nil.

3. Use the WaitForSingleObject () function before synchronizing the code. This function allows the thread to take ownership of the mutex object (synchronous code). The function is defined as:

DWORD WINAPI WaitForSingleObject (

HANDLE Hhandle,

DWORD dwmilliseconds);

This function allows the current thread to sleep within the specified time of dwmilliseconds until the object specified by the Hhandle parameter enters the signaled state. When a mutex is no longer owned by the thread, it enters the signaled state. When a process is to be terminated, it enters the signaled state. The dwmilliseconds parameter can be set to 0, which means that only the object specified by the Hhandle parameter is signaled and returned immediately. The dwmilliseconds parameter is set to infinite, which means that if the signal does not appear it will be kept waiting.

The return value of this function means:

The object specified by Wait_abandoned is a mutex object, and the thread that owns the mutex terminates before the object is disposed of. At this point, the mutex object is called discarded. In this case, the mutex is owned by the current thread and is set to a non-signaled state

WAIT_OBJECT_0 the specified object is in signaled state

Wait_timeout wait time has gone, the object is still non-signaled state

Again, when a mutex is no longer owned by a thread, it is signaled. The thread that first calls the WaitForSingleObject () function becomes the owner of the mutex, and the mutex is set to no signaled state. When a thread calls the ReleaseMutex () function and passes a handle to a mutex as a parameter, the owning relationship is lifted and the mutex is re-entered in the signaled state.

Note that in addition to the WaitForSingleObject () function, you can also use the Waitformultipleobject () and Msgwaitformultipleobject () functions, which can wait for several objects to become signaled. For more information on these two functions, see the Win32 API online documentation.

4, after the synchronization code ends, use the ReleaseMutex (thandle) function to flag. This function simply frees the owner relationship of the mutex object and the thread, and does not release the handle to the mutex.

5. Call CloseHandle (Thandle) to close the mutex object. Notice where the function is used in the routine.

Simultaneous read and write global Data of Delphi multithreaded programming

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.