我想同步线程来访问一个公共变量。 想象一下,我有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