Allow only 3 instances of an application using semaphores

后端 未结 3 612
生来不讨喜
生来不讨喜 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:46

    1. You must try to see if it was created
    2. You must use one of the wait function to see if you can get a count
    3. At the end, you must release the lock & handle so that it can work the next time user close and open your app

    Cheers

    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; 
    

提交回复
热议问题