Advertisement
piffy

Semafori windows (demo)

Sep 4th, 2014
349
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.40 KB | None | 0 0
  1. #include <windows.h>
  2. #include <stdio.h>
  3. HANDLE CreaNuovoSemaforo(LPSECURITY_ATTRIBUTES lpsa, LONG cInitial, LONG cMax, LPTSTR lpszName)  {
  4. HANDLE hSem;
  5. hSem = CreateSemaphore(
  6.     lpsa,// parametri di sicurezza
  7.     cInitial,// valore iniziale
  8.     cMax,// valore massimo
  9.     lpszName);// Puntatore al nome del semaforo
  10. if (hSem == NULL && GetLastError() == ERROR_ALREADY_EXISTS)
  11.         {CloseHandle(hSem);return NULL;}
  12. else
  13.            {printf("CreateNewSemaphore(): successo \n");}
  14. return hSem;
  15. }
  16.  
  17. bool AspettaIlVerde(HANDLE hSem) {
  18. DWORD dwWaitResult = WaitForSingleObject(
  19.       hSem,  // handle del semaforo
  20.       0L);  // timeout (può essere INFINITE)
  21. if (dwWaitResult==WAIT_OBJECT_0)
  22. {
  23. printf("Semaforo verde..\n");
  24. return true;
  25. }
  26. return false;}
  27.  
  28. int RilasciaSemaforo(HANDLE hSem){
  29.  
  30. if (!ReleaseSemaphore(
  31.     hSem,  // handle del semaforo
  32.     1,  // incrementa di uno il contatore        
  33.     NULL))  // non interessa il valore precedente
  34.     {
  35.     printf("ReleaseSemaphore() fallita, errore %d.\n",GetLastError());
  36.     }
  37. else
  38.        printf("ReleaseSemaphore() va bene.\n");
  39.        return 0;
  40. }
  41.      
  42. int main(){
  43. LPSECURITY_ATTRIBUTES lpsa = NULL;
  44. LONG cInitial = 0;
  45. LONG cMax = 10;
  46. LPTSTR lpszName = "SemaforoUno";
  47. HANDLE hSem = CreaNuovoSemaforo(lpsa, cInitial, lpszName);
  48.  
  49. if (AspettaIlVerde(hSem)){
  50.     /* sezione critica */
  51.     RilasciaSemaforo(hSem);
  52.     }
  53.  
  54. CloseHandle(hSem); ExitProcess(0);
  55. return 0;
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement