TryEnterCriticalSection()不同于EnterCriticalSection()的声明在于多出一个布尔型的返回
值,如果返回True代表成功进入临界区,如果返回False代表临界区已占用且不进入临界
区。运用这个函数,线程能够迅速查看它是否可以访问某个共享资源,如果不能访问,那么
它可以继续执行某些其他操作,而不必进行等待。
使用TryEnterCriticalSection(),必须判断其返回值。
当你不需要临界区时,应当调用DeleteCriticalSection()过程删除临界区,该函数多半在窗
体销毁时或程序终止前执行。下面是它的声明:
procedureDeleteCriticalSection(varlpCriticalSection:TRTLCriticalSection);stdcall;
例:
type
TMyThread=class(TThread)
protected
procedureExecute;override;
public
constructorCreate;virtual;
end;
var
Form1:TForm1;
CriticalSection:TRTLCriticalSection;//定义临界区
implementation
{$R*.dfm}
var
tick:Integer=1;
3
procedureTMyThread.Execute;
begin
EnterCriticalSection(CriticalSection);//进入临界区
try
Form1.Edit1.Text:=IntToStr(tick);
Inc(tick);
Sleep(10);
finally
LeaveCriticalSection(CriticalSection);//离开临界区
end;
end;
constructorTMyThread.Create;
begin
inheritedCreate(False);
FreeOnTerminate:=True;
end;
procedureTForm1.RzButton1Click(Sender:TObject);
var
index:Integer;
begin
forindex:=0to15do
TMyThread.Create;
end;
procedureTForm1.FormCreate(Sender:TObject);
begin
InitializeCriticalSection(CriticalSection);//初始化临界区
end;
procedureTForm1.FormDestroy(Sender:TObject);
begin
DeleteCriticalSection(CriticalSection);//删除临界区
end;
(2).使用TcriticalSection类
TcriticalSection是在SyncObjs单元中定义的类,要使用它需要先usesSyncObjs。它对上
面的那些临界区操作API函数进行了封装,简化并方便了在Delphi中的使用。例如
TcriticalSection.Enter其实是调用了TRTLCriticalSection.Enter。
使用TcriticalSection类和一般类差不多,首先实例化TcriticalSection类。使用的时候只要
在主线程当中创建这个临界对象(注意一定要在需要同步的子线程之外建立这个对象)。
Tcriticalsection类的构造函数比较简单,没有带参数。
本文来自电脑杂谈,转载请注明本文网址:
https://www.pc-fly.com/a/jisuanjixue/article-32871-14.html
非权力非战略能定而