在編寫多執行緒應用程式時,最重要的是控制好執行緒間的同步資源訪問,以確保執行緒的安全運行。 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;