仅允许使用信号量的3个应用程序实例

opc*_*0de 6 delphi semaphore

我正在尝试使用信号量实现一个简单的例程,这将允许我只运行3个应用程序实例.我可以使用3个互斥锁,但到目前为止,这不是一个很好的方法

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;
Run Code Online (Sandbox Code Playgroud)

我该怎么做呢?

gab*_*abr 16

始终确保释放信号量,因为如果应用程序死亡,则不会自动执行此操作.

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.
Run Code Online (Sandbox Code Playgroud)


Ond*_*lle 5

你可以使用TJclAppInstancesJCL.