Advertisement
piffy

Semafori windows (prod_cons)

Sep 4th, 2014
455
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.73 KB | None | 0 0
  1. #include <windows.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4.  
  5. #define DIM 1024
  6. char buffer[DIM];
  7. LPCTSTR nome = "EsempioSemaforo";
  8. HANDLE sem_t;
  9.  
  10. DWORD WINAPI thread_function(PVOID arg) {
  11.    LONG dwSemCount;
  12.    HANDLE hSemaphore = OpenSemaphore( SYNCHRONIZE |
  13. SEMAPHORE_MODIFY_STATE, FALSE, nome );
  14.  
  15.    WaitForSingleObject( hSemaphore, INFINITE );
  16.    while(strncmp("stop", buffer, 4) != 0) {
  17.        printf("Ha inserito %d caratteri\n", strlen(buffer) -1);
  18.        ReleaseSemaphore(hSemaphore, 1, &dwSemCount);
  19.        WaitForSingleObject( hSemaphore, INFINITE );
  20.    }
  21.    ReleaseSemaphore(hSemaphore, 1, &dwSemCount);
  22.    CloseHandle( hSemaphore );
  23.    return 0;
  24. }
  25.  
  26. int main() {
  27.     HANDLE a_thread;
  28.     DWORD a_threadId;
  29.     DWORD thread_result;
  30.     LONG dwSemCount;
  31.  
  32. // Inizializza un semaforo.
  33.   sem_t = CreateSemaphore( NULL, 0, 1, nome );
  34.  
  35.   if (sem_t == NULL) {
  36.         perror("Inizializzazione del semaforo fallita");
  37.         exit(EXIT_FAILURE);
  38.     }
  39.  
  40. // Crea un secondo thread.
  41.     a_thread = CreateThread(NULL, 0, thread_function, (PVOID)NULL, 0,
  42. &a_threadId);
  43.  
  44.     if (a_thread == NULL) {
  45.         perror("Creazione del thread fallita");
  46.         exit(EXIT_FAILURE);
  47.     }
  48.  
  49.     printf("Scrivi qualcosa ('stop' per uscire)\n");
  50.     while(strncmp("stop", buffer, 4) != 0) {
  51.         fgets(buffer, DIM, stdin);
  52.         ReleaseSemaphore(sem_t, 1, &dwSemCount);
  53.     WaitForSingleObject(sem_t, INFINITE);
  54.     }
  55.  
  56.     printf("\nAttenti la fine del thread...\n");
  57.     if (WaitForSingleObject(a_thread, INFINITE) != WAIT_OBJECT_0) {
  58.         perror("Riunione thread fallita");
  59.         exit(EXIT_FAILURE);
  60.     }
  61.  
  62.     GetExitCodeThread(a_thread, &thread_result);
  63.     printf("\nThread riuniti\n");
  64.     exit(EXIT_SUCCESS);
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement