Extended Delphi thread synchronization object (1)

zhaozj2021-02-11  243

Delphi's extended thread synchronization object (1) [Author: Yu Hua Add Time: 2001-5-5 18:01:08]

Source: www.ccidnet.com

When writing multithreaded applications, the most important is to control synchronous resource access between threads to ensure the safe operation of threads. Win 32 API provides a set of synchronous objects, such as Semaphore, Mutex, critical, and events, etc., is used to solve this problem.

Delphi encapsulates event objects and critical area objects to TEVENT objects and TcritialSECTION objects, making the two objects simple and convenient. However, if you want to use a signal or mutual exclusion in a Delphi program, you must use the complex Win32 API function, which is very inconvenient for programmers who are not familiar with the Win32 API function. Therefore, the author uses Delphi to construct two classes, encapsulated signal lights and mutex (Tsemaphore and Tmutex, respectively, I hope to help the Vast Delphi programmer.

First, the structure of the class

Let's abstall the Win32 API's signal light objects and mutual exclusive objects, construct a parent THANDLEOBJECTEX, and then derived two subclasses Tsemphore and TMutex by this parent class.

The source code of the class is as follows:

UNIT SYNCOBJSEX;

Interface

Uses Windows, Messages, Sysutils, Classes, Syncobjs;

Type

ThandleObjectEx = Class (ThandleObject)

// THANDLEOBJECTEX is the parent class of mutex and signal lights.

protected

Fhandle: Thandle;

Flasterror: integer;

public

DESTRUCTOR DESTROY; OVERRIDE;

PROCEDURE Release; OVERRIDE;

Function Waitfor (Timeout: DWORD): TWAITRESULT;

Property Lasterror: Integer Read Flasterror;

Property Handle: Thandle Read Fhandle;

END;

TMUTEX = Class (THANDLEOBJECTEX) // Mutually exclusive class

public

CONSTRUCTOR CREATE (Mutexattributes: psecurityattributes; initialowner: boolean; const name: string);

PROCEDURE Release; OVERRIDE;

END;

TSEMAPHORE = Class (ThandleObjectex)

// signal light

public

CONSTRUCTOR CREGES: PsecurityAttributes; InitialCount: Integer; MaximumCount: Integer; Const Name: String

Procedure Release (ReleaseCount: Integer = 1; PreviousCount: Pointer = NIL); overload;

转载请注明原文地址:https://www.9cbs.com/read-3901.html

New Post(0)