Advertisement
Guest User

Untitled

a guest
Dec 19th, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.39 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <pthread.h>
  3. #include <unistd.h>
  4.  
  5. void* watek(void* arg);
  6.  
  7. FILE *plik;
  8. char buffor[100];
  9. pthread_mutex_t mutexDostepDoPliku;
  10. volatile int isBufferFull = 0;
  11.  
  12. int main() {
  13.     plik = fopen("buczko_mutex.c" , "r");
  14.     if( plik == NULL )
  15.     {
  16.         fprintf(stderr, "Nie moge uzyskac dostepu do pliku");
  17.         return -1;
  18.     }
  19.     pthread_mutex_init(&mutexDostepDoPliku, NULL);
  20.     pthread_t watek1, watek2, watek3;
  21.     pthread_attr_t atrybuty;
  22.     pthread_attr_init(&atrybuty);
  23.     pthread_attr_setdetachstate(&atrybuty, PTHREAD_CREATE_DETACHED);
  24.     pthread_create(&watek1, &atrybuty, &watek, NULL);
  25.     pthread_create(&watek2, &atrybuty, &watek, NULL);
  26.     pthread_create(&watek3, &atrybuty, &watek, NULL);
  27.     while (1) {
  28.         pthread_mutex_lock(&mutexDostepDoPliku);
  29.         if (fgets(buffor,100, plik) == NULL) break;
  30.         isBufferFull = 1;
  31.         pthread_mutex_unlock(&mutexDostepDoPliku);
  32.         while(isBufferFull);
  33.     }
  34.     fclose(plik);
  35.     return 0;
  36. }
  37.  
  38. void* watek(void* arg)
  39. {
  40.     pthread_t id = pthread_self();
  41.  
  42.     while(1) {
  43.         if(isBufferFull)
  44.         {
  45.             pthread_mutex_lock(&mutexDostepDoPliku);
  46.             if(isBufferFull) {
  47.                 printf("%ld:%s", id, buffor);
  48.                 isBufferFull = 0;
  49.             }
  50.                 pthread_mutex_unlock(&mutexDostepDoPliku);
  51.         }
  52.     }
  53.     return NULL;
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement