(CriticalSection)和事件(Event)等
Delphi分別將事件對象和臨界區對象封裝為Tevent對象和TcritialSection對象
一
我們先對Win
類的源代碼如下
unit SyncobjsEx;
interface
uses Windows
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=
overload;
end;
implementation
{ THandleObjectEx }//父類的實現
destructor THandleObjectEx
begin
Windows
inherited Destroy;
end;
procedure THandleObjectEx
begin
end;
function THandleObjectEx
//等待函數
begin
case WaitForSingleObject(Handle
WAIT_ABANDONED: Result := wrAbandoned;
//無信號
WAIT_OBJECT_
//有信號
WAIT_TIMEOUT: Result := wrTimeout;//超時
WAIT_FAILED://失敗
begin
Result := wrError;
FLastError := GetLastError;
end;
else
Result := wrError;
end;
end;
{ TSemaphore }//信號燈類的實現
constructor TSemaphore
InitialCount
begin
FHandle := CreateSemaphore
(SemaphoreAttributes
//四個參數分別為
end;
procedure TSemaphore
//信號燈類的Release方法
begin
Windows
end;
{ TMutex }//互斥類的實現
constructor TMutex
InitialOwner: Boolean; const Name: string);
//互斥類的構造函數
begin
FHandle := CreateMutex(MutexAttributes
end;
procedure TMutex
begin
Windows
end;
end;
二
信號燈對象維持一個從
用類的Create方法來建立信號燈對象
Semaphore := TSemaphore
一般把信號燈的初始計數設置成最大值
信號燈用法舉例
if wrSignaled = Semaphore
begin
//打開另一個窗口
end
Semaphore
在線程建立窗口之前
Mutex對象的狀態在它不被任何線程擁有時是有信號的
用類的Create方法建立Mutex 對象
Mutex := TMutex
在完成對共享資源的訪問後
互斥對象用法舉例如下
if wrSignaled = Mutex
begin
try
//往數據庫寫入
finally
Mutex
end;
end;
上述類代碼在Windows
From:http://tw.wingwit.com/Article/program/Delphi/201311/8521.html