Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <windows.h>
- #include <stdio.h>
- HANDLE CreaNuovoSemaforo(LPSECURITY_ATTRIBUTES lpsa, LONG cInitial, LONG cMax, LPTSTR lpszName) {
- HANDLE hSem;
- hSem = CreateSemaphore(
- lpsa,// parametri di sicurezza
- cInitial,// valore iniziale
- cMax,// valore massimo
- lpszName);// Puntatore al nome del semaforo
- if (hSem == NULL && GetLastError() == ERROR_ALREADY_EXISTS)
- {CloseHandle(hSem);return NULL;}
- else
- {printf("CreateNewSemaphore(): successo \n");}
- return hSem;
- }
- bool AspettaIlVerde(HANDLE hSem) {
- DWORD dwWaitResult = WaitForSingleObject(
- hSem, // handle del semaforo
- 0L); // timeout (può essere INFINITE)
- if (dwWaitResult==WAIT_OBJECT_0)
- {
- printf("Semaforo verde..\n");
- return true;
- }
- return false;}
- int RilasciaSemaforo(HANDLE hSem){
- if (!ReleaseSemaphore(
- hSem, // handle del semaforo
- 1, // incrementa di uno il contatore
- NULL)) // non interessa il valore precedente
- {
- printf("ReleaseSemaphore() fallita, errore %d.\n",GetLastError());
- }
- else
- printf("ReleaseSemaphore() va bene.\n");
- return 0;
- }
- int main(){
- LPSECURITY_ATTRIBUTES lpsa = NULL;
- LONG cInitial = 0;
- LONG cMax = 10;
- LPTSTR lpszName = "SemaforoUno";
- HANDLE hSem = CreaNuovoSemaforo(lpsa, cInitial, lpszName);
- if (AspettaIlVerde(hSem)){
- /* sezione critica */
- RilasciaSemaforo(hSem);
- }
- CloseHandle(hSem); ExitProcess(0);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement