Advertisement
Guest User

Zad2 - mutex

a guest
Dec 11th, 2019
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.13 KB | None | 0 0
  1. #include "stdio.h"
  2. #include "unistd.h"
  3. #include "pthread.h"
  4. #include "stdlib.h"
  5. #include "errno.h"
  6. #include "limits.h"
  7. #include "math.h"
  8. #include "semaphore.h"
  9. #include "string.h"
  10. #define BUFFER_SIZE 100
  11.  
  12. pthread_mutex_t mut[4];
  13.  
  14. void emptyBuffer( char* buff);
  15. void *threadCzytelnik(void *arg);
  16.  
  17. struct targs{
  18.     int numWatku;
  19. };
  20. char common[BUFFER_SIZE];
  21. int koniecPliku = 0;
  22. int main()
  23. {
  24.     FILE *fp;
  25.     emptyBuffer(common);
  26.     for(int i = 0; i < 4; i++)
  27.     pthread_mutex_init(&mut[i], NULL);
  28.     pthread_attr_t attrs;
  29.     pthread_attr_init(&attrs);
  30.     //pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED );
  31.    
  32.     pthread_t threadId[3];
  33.     fp = fopen("/etc/passwd","r");
  34.     struct targs watki[3];
  35.     {
  36.         int i = 0;
  37.         for(;i < 3; i++)
  38.         {
  39.             watki[i].numWatku = i+1;
  40.             pthread_create(&threadId[i], &attrs, threadCzytelnik, &watki[i]);
  41.             pthread_detach(threadId[i]);
  42.         }
  43.     }
  44.     pthread_mutex_lock(&mut[1]);
  45.     pthread_mutex_lock(&mut[2]);
  46.     pthread_mutex_lock(&mut[3]);
  47.     char *l;
  48.     int i = 0;
  49.     while( 1 ) {
  50.         pthread_mutex_lock(&mut[0]);
  51.         l = fgets(common, BUFFER_SIZE, fp);
  52.         if(l==0) break;
  53.         pthread_mutex_unlock(&mut[1]);
  54.     }
  55.     fclose(fp);
  56.     koniecPliku = 1;
  57.    
  58. }
  59.  
  60. void emptyBuffer( char* buff)
  61. {
  62.     {
  63.         int i = 0;
  64.         for(;i<BUFFER_SIZE;i++)
  65.         {
  66.             buff[i] = 0;
  67.         }
  68.     }
  69. }
  70.  
  71.  
  72. void *threadCzytelnik(void *arg)
  73. {
  74.  
  75.     struct targs *argptr = (struct targs*) arg;
  76.    
  77.     char nazwaPliku[80];
  78.     int num = argptr->numWatku;
  79.     snprintf(nazwaPliku, 80, "./MATEUSZ%d", num);
  80.     FILE *fp = fopen(nazwaPliku, "w");
  81.     while(1)
  82.     {
  83.         pthread_mutex_lock(&mut[num]);
  84.             if(koniecPliku)
  85.             {
  86.                 fflush(fp);
  87.                 fclose(fp);
  88.                 pthread_exit(0);
  89.             }
  90.             fwrite(common, sizeof(char), strlen(common), fp);
  91.             printf("%d-%s\n", argptr->numWatku, common);
  92.             fflush(stdout);
  93.             pthread_mutex_unlock(&mut[(num + 1)%4]);
  94.  
  95.     }
  96. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement