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

时间:2011-09-18 10:38:32

标签: 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;

我该如何正确地做到这一点?

3 个答案:

答案 0 :(得分: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.

答案 1 :(得分:5)

您可以使用TJclAppInstances中的JCL

答案 2 :(得分:2)

  1. 您必须尝试查看是否已创建
  2. 您必须使用其中一个等待功能来查看是否可以获得点数
  3. 最后,你必须释放锁和&amp;处理,以便下次用户关闭并打开您的应用程序时可以正常工作
  4. 干杯

    var
      hSem: THandle;
    begin
      hSem := OpenSemaphore(nil, SEMAPHORE_ALL_ACCESS, True, 'MySemp3');
      if hSem = 0 then
        hSem := CreateSemaphore(nil, 3, 3,'MySemp3');
    
      if hSem = 0 then
      begin
        ShowMessage('... show the error');
        Halt(1);
        Exit;     
      end;
    
      if WaitForSingleObject(hSem, 0) <> WAIT_OBJECT_0 then
      begin
        CloseHandle(hSem);
        ShowMessage('Application can be runed only 3 times at once');
        Halt(1);
        Exit; 
      end;
    
      try   
        your application.run codes..
    
      finally
        ReleaseSemaphore(hSem, 1, nil);
        CloseHandle(hSem);
      end;