我想同步線程來訪問一個公共變量。 想象一下,我有N個線程,每個線程都可以訪問一個類型爲TSyncThreds的變量的全局實例。TCriticalSection是否允許多線程訪問變量?
我可以調用IncCount,DecCount方法嗎?或者,我會遇到併發線程訪問同一個對象實例的問題?
我只是syncronize的訪問FCcounter變量...
type
TSyncThreads = class
public
FCounterGuard: TCriticalSection;
FCounter: integer;
FSimpleEvent: TSimpleEvent;
constructor Create();
procedure Wait();
procedure IncCounter();
procedure DecCounter();
end;
var
SyncThread: TSyncThreads;
implementation
uses
Math, Windows, Dialogs;
{ TSyncThreads }
procedure TSyncThreads.DecCounter;
begin
FCounterGuard.Acquire;
Dec(FCounter);
if FCounter = 0 then
FSimpleEvent.SetEvent;
FCounterGuard.Release;
end;
procedure TSyncThreads.IncCounter;
begin
FCounterGuard.Acquire;
Inc(FCounter);
FCounterGuard.Release;
end;
constructor TSyncThreads.Create();
begin
FCounter := 0;
FSimpleEvent := TSimpleEvent.Create;
FCounterGuard := TCriticalSection.Create;
FSimpleEvent.ResetEvent;
end;
procedure TSyncThreads.Wait;
var
ret: TWaitResult;
begin
ret := FSimpleEvent.WaitFor(INFINITE);
end;
您應該使用try/finally塊將調用包裝爲Acquure/Release,以確保在按住關鍵部分時出現問題時調用Release。否則,它可能永遠不會釋放,無論等待獲得什麼,都會受到阻止。 – 2011-07-15 07:36:23