在編寫多線程應用程序時,最重要的是控制好線程間的同步資源訪問,以保證線程的安全運行。Win 32 API提供了一組同步對象,如:信號燈(Semaphore)、互斥(Mutex)、臨界區(CriticalSection)和事件(Event)等,用來解決這個問題。
Delphi分別將事件對象和臨界區對象封裝為Tevent對象和TcritialSection對象,使得這兩個對象的使用簡單且方便。但是如果在Delphi程序中要使用信號燈或互斥等對象就必須借助於復雜的Win32 API函數,這對那些不熟悉Win32 API函數的編程人員來說很不方便。因此,筆者用Delphi構造了兩個類,對信號燈和互斥對象進行了封裝(分別為TSemaphore和TMutex),希望對廣大Delphi編程人員有所幫助。
一、類的構造
我們先對Win32 API的信號燈對象和互斥對象進行抽象,構造一個父類THandleObjectEx,然後由這個父類派生出兩個子類Tsemphore和Tmutex。
類的源代碼如下:
unit SyncobJSEx;
interface
uses Windows,Messages,SysUtils,Classes,SyncobJS;
type
THandleObjectEx = class(THandleObject)
// THandleObjectEx為互斥類和信號燈類的父類
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)//互斥類
public
constructor Create(MutexAttributes: PSecurityAttributes; InitialOwner: Boolean;const Name:string);
procedure Release; override;
end;
TSemaphore = class(THandleObjectEx)
//信號燈類
public
constructor Create(SemaphoreAttributes: PSecurityAttributes;InitialCount:Integer;MaximumCount: integer; const Name: string);
procedure Release(ReleaseCount: Integer=1;PreviousCount:Pointer=nil);overload;
end;
implementation
{ THandleObjectEx }//父類的實現
destructor THandleObjectEx.Destroy;
begin
Windows.CloseHandle(FHandle);
inherited Destroy;
end;
procedure THandleObjectEx.Release;
begin
end;
function THandleObjectEx.WaitFor(Timeout: DWord): TWaitResult;
//等待函數,參數為等待時間
begin
case WaitForSingleObject(Handle, Timeout) of
WAIT_ABANDONED: Result := wrAbandoned;
//無信號
WAIT_OBJECT_0: Result := wrSignaled;
//有信號
WAIT_TIMEOUT: Result := wrTimeout;//超時
WAIT_FAILED://失敗
begin
Result := wrError;
FLastError := GetLastError;
end;
else
Result := wrError;
end;
end;
{ TSemaphore }//信號燈類的實現
constructor TSemaphore.Create(SemaphoreAttributes: PSecurityAttributes;
InitialCount, MaximumCount: integer; const Name: string);//信號燈類的構造函數
begin
FHandle := CreateSemaphore
(SemaphoreAttributes,InitialCount,
MaximumCount,PChar(Name));
//四個參數分別為:安全屬性、初始信號燈計數、最大信號燈計數、信號燈名字
end;
procedure TSemaphore.Release(ReleaseCount: Integer=1; PreviousCount: Pointer=nil);
//信號燈類的Release方法,每執行一次按指定量增加信號燈計數
begin
Windows.ReleaseSemaphore(FHandle, ReleaseCount, PreviousCount);
end;
{ TMutex }//互斥類的實現
constructor TMutex.Create(MutexAttributes: PSecurityAttributes;
InitialOwner: Boolean; const Name: string);
//互斥類的構造函數
begin
FHandle := CreateMutex(MutexAttributes, InitialOwner, PChar(Name));
end;
procedure TMutex.Release;//互斥類的Release方法,用來釋放對互斥對象的