Advertisement
Guest User

Untitled

a guest
Dec 19th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.25 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <pthread.h>
  3. #include <unistd.h>
  4. #include <stdbool.h>
  5.  
  6. #define NAZWA_PLIKU "buczko_mutexy.c"
  7. #define WIELKOSC_BUFORA 100
  8. #define ILOSC_WATKOW 3
  9.  
  10. void* watek(void* arg);
  11.  
  12. FILE *plik;
  13. char buffor[WIELKOSC_BUFORA];
  14. pthread_mutex_t mutexDostepDoBufora;
  15. volatile int czyBuforPelny = 0;
  16. volatile int czyZakonczonoOdczyt = 0;
  17. pthread_cond_t czyBufforNiepusty;
  18. pthread_t watki[ILOSC_WATKOW];
  19. pthread_attr_t atrybuty;
  20.  
  21. int main() {
  22.     plik = fopen(NAZWA_PLIKU , "r");
  23.     if ( plik == NULL ) {
  24.         fprintf(stderr, "Nie moge uzystakc dostepu do pliku.\n");
  25.         return -1;
  26.     }
  27.  
  28.     pthread_mutex_init(&mutexDostepDoBufora, NULL);
  29.     pthread_cond_init(&czyBufforNiepusty, NULL);
  30.     pthread_attr_init(&atrybuty);
  31.     pthread_attr_setdetachstate(&atrybuty, PTHREAD_CREATE_DETACHED);
  32.  
  33.     bool bledyTworzeniaWatkow = false;
  34.     for (int i = 0; i<ILOSC_WATKOW; i++)
  35.         bledyTworzeniaWatkow |= pthread_create(&(watki[i]), &atrybuty, &watek, NULL);
  36.  
  37.     if ( bledyTworzeniaWatkow ) {
  38.         fprintf(stderr, "Nie moge utworzyc watkow.\n");
  39.         return -2;
  40.     }
  41.  
  42.     do {
  43.         pthread_mutex_lock(&mutexDostepDoBufora);
  44.         if ( fgets(buffor,100, plik ) == NULL) {
  45.             fclose(plik);
  46.             czyZakonczonoOdczyt = 1;
  47.             break;
  48.         }
  49.         czyBuforPelny = 1;
  50.         pthread_cond_broadcast(&czyBufforNiepusty);
  51.         pthread_cond_wait(&czyBufforNiepusty, &mutexDostepDoBufora);
  52.         pthread_mutex_unlock(&mutexDostepDoBufora);
  53.     } while (1);
  54.     pthread_attr_destroy(&atrybuty);
  55.     pthread_mutex_destroy(&mutexDostepDoBufora);
  56.     return 0;
  57. }
  58.  
  59. void* watek(void* arg)
  60. {
  61.     pthread_t id = pthread_self();
  62.  
  63.     do {
  64.         pthread_mutex_lock(&mutexDostepDoBufora);
  65.         if(czyBuforPelny) {
  66.             printf("%ld:%s", (long)id, buffor);
  67.             czyBuforPelny = 0;
  68.             pthread_cond_broadcast(&czyBufforNiepusty);
  69.         } else {
  70.             if ( czyZakonczonoOdczyt ) {
  71.                 pthread_mutex_unlock(&mutexDostepDoBufora);
  72.                 break;
  73.             }
  74.             pthread_cond_wait(&czyBufforNiepusty, &mutexDostepDoBufora);
  75.         }
  76.         pthread_mutex_unlock(&mutexDostepDoBufora);
  77.     } while ( 1 );
  78.     return NULL;
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement