Allow only 3 instances of an application using semaphores

后端 未结 3 611
生来不讨喜
生来不讨喜 2021-02-09 13:09

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

3条回答
  •  青春惊慌失措
    2021-02-09 13:44

    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.
    

提交回复
热议问题