2011-09-18 11 views
6

Sto tentando di implementare una semplice routine utilizzando i semafori che mi consentiranno di eseguire solo 3 istanze dell'applicazione. Potrei usare 3 mutex ma non è un buon approccio ho provato fino ad oraConsenti solo 3 istanze di un'applicazione utilizzando i semafori

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; 

Come posso farlo correttamente?

risposta

16

Assicurati sempre di rilasciare un semaforo perché questo non viene eseguito automaticamente se l'applicazione muore.

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. 
+0

Grande codificatore, ottima risposta. Grazie ! – opc0de

+0

+1 Un po 'deludente per il fatto che 'SyncObjs.TSemaphore' non soddisfa le attese temporizzate. O mi sono perso qualcosa. –

+0

D2007 non ha nemmeno SyncObjs.TSemaphore ... In XE, sei corretto - puoi aspettare con timeout 0 in Linux ma non su Windows. Stupid – gabr

2
  1. Dovete provare a vedere se è stato creato
  2. È necessario utilizzare una delle funzioni di attesa per vedere se è possibile ottenere un conteggio
  3. Alla fine, è necessario rilasciare il blocco & gestire in modo che possa lavorare la prossima volta l'utente chiudere e aprire l'app

Acclamazioni

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; 
Problemi correlati