var
Form1:TForm1;
HSem:THandle=0;//定义一个信号量
implementation
var
tick:Integer=0;
procedureTMyThread.Execute;
var
WaitReturn:DWord;
begin
WaitReturn:=WaitForSingleObject(HSem,INFINITE);//使用信号量对象,信号量减1
Form1.Edit1.Text:=IntToStr(tick);
Inc(tick);
Sleep(10);
ReleaseSemaphore(HSem,1,Nil);//释放信号量对象,信号量加1
end;
…
procedureTForm1.FormCreate(Sender:TObject);
begin
HSem:=CreateSemaphore(Nil,1,1,Nil);//创建信号量对象
end;
procedureTForm1.FormDestroy(Sender:TObject);
begin
CloseHandle(HSem);//销毁信号量
end;
procedureTForm1.Button1Click(Sender:TObject);
var
index:Integer;
begin
forindex:=0to10do
TMyThread.Create;
end;
(2).使用TSemaphore类
TSemaphore是在SyncObjs单元中定义的类,其是ThandleObject类的子类,要使用它需
要先usesSyncObjs。它对上面的API函数进行了封装,简化并方便了在Delphi中的使
用。
其有三个版本的构造器,简单执行TSemaphore.Create就可实例化一个对象:
constructorCreate(UseCOMWait:Boolean=False);overload;
constructorCreate(SemaphoreAttributes:PSecurityAttributes;AInitialCount:Integer;
AMaximumCount:Integer;constName:string;UseCOMWait:Boolean=False);overload;
constructorCreate(DesiredAccess:LongWord;InheritHandle:Boolean;
constName:string;UseCOMWait:Boolean=False);overload;
参数参见上面介绍。
TSemaphore.Acquire等效于WaitForSingleObject(semaphorehandle,INFINITE),其实际上就
是执行THandleObject.WaitFor(INFINITE)。或者使用WaitFor()和WaitForMultiple()函数,
这两个函数可以设置等待的时间或等待多个事件对象。
TSemaphore.Release有两个版本,声明如下:
procedureRelease;override;overload;
functionRelease(AReleaseCount:Integer):Integer;overload;reintroduce;
第一个版本实际执行ReleaseSemaphore(FHandle,1,nil)
第二个版本AReleaseCount参数表示释放时增加的信号量计数值,返回值是释放前的信号
本文来自电脑杂谈,转载请注明本文网址:
https://www.pc-fly.com/a/jisuanjixue/article-32871-8.html
“不喜欢”“我记得你以前不是喜欢易烊千玺吗