本文介绍了只允许3个实例的应用程序使用信号量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用信号量来实现一个简单的例程,这将允许我只运行3个应用程序的实例。我可以使用3个互斥体,但这不是一个很好的方法,我试过这个到目前为止
I am trying to implement a simple routine using semaphores that will allow me to run only 3 instances of the application. I could use 3 mutexes but that is not a nice approach i tried this so far
var
hSem:THandle;
begin
hSem := CreateSemaphore(nil,3,3,'MySemp3');
if hSem = 0 then
begin
ShowMessage('Application can be run only 3 times at once');
Halt(1);
end;
如何正确执行?
推荐答案
始终确保您释放信号量,因为如果您的应用程序死亡,则不会自动完成。
Always make sure that you release a semaphore because this is not done automatically if your application dies.
program Project72;
{$APPTYPE CONSOLE}
uses
Windows,
SysUtils;
var
hSem: THandle;
begin
try
hSem := CreateSemaphore(nil, 3, 3, 'C15F8F92-2620-4F3C-B8EA-A27285F870DC/myApp');
Win32Check(hSem <> 0);
try
if WaitForSingleObject(hSem, 0) <> WAIT_OBJECT_0 then
Writeln('Cannot execute, 3 instances already running')
else begin
try
// place your code here
Writeln('Running, press Enter to stop ...');
Readln;
finally ReleaseSemaphore(hSem, 1, nil); end;
end;
finally CloseHandle(hSem); end;
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
end.
这篇关于只允许3个实例的应用程序使用信号量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!