Allow only 3 instances of the application using semaphores

I am trying to implement a simple procedure using semaphores that will allow me to run only 3 instances of the application. I could use 3 mutex, but this is not a good approach. I have 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; 

How can I do it right?

+6
source share
3 answers

Always make sure that you release the semaphore, because it does not run 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. 
+16
source

You can use TJclAppInstances from the JCL .

+5
source
  • You should try to see if it was created.
  • You must use one of the wait functions to find out if you can get a counter.
  • In the end, you must release the lock and handle so that it can work the next time the user closes and opens your application.

Greetings

 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; 
+2
source

Source: https://habr.com/ru/post/897563/


All Articles