Advertisement
Guest User

kedzierski mutex

a guest
Dec 10th, 2019
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.22 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. sem_t wr, rd1, rd2, rd3;
  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.     sem_init(&wr, 0, 1);
  27.     sem_init(&rd1, 0, 0);
  28.     sem_init(&rd2, 0, 0);
  29.     sem_init(&rd3, 0, 0);
  30.     pthread_attr_t attrs;
  31.     pthread_attr_init(&attrs);
  32.     //pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED );
  33.    
  34.     pthread_t threadId[3];
  35.     fp = fopen("/etc/passwd","r");
  36.     struct targs watki[3];
  37.     {
  38.         int i = 0;
  39.         for(;i < 3; i++)
  40.         {
  41.             watki[i].numWatku = i+1;
  42.             pthread_create(&threadId[i], &attrs, threadCzytelnik, &watki[i]);
  43.             pthread_detach(threadId[i]);
  44.         }
  45.     }
  46.     char *l;
  47.     while( 1 ) {
  48.         sem_wait(&wr);
  49.         l = fgets(common, BUFFER_SIZE, fp);
  50.         if(l==0) break;
  51.         sem_post(&rd1);
  52.        
  53.     }
  54.     fclose(fp);
  55.     koniecPliku = 1;
  56.     sem_post(&rd1);
  57. }
  58.  
  59. void emptyBuffer( char* buff)
  60. {
  61.     {
  62.         int i = 0;
  63.         for(;i<BUFFER_SIZE;i++)
  64.         {
  65.             buff[i] = 0;
  66.         }
  67.     }
  68. }
  69.  
  70.  
  71. void *threadCzytelnik(void *arg)
  72. {
  73.     struct targs *argptr = (struct targs*) arg;
  74.    
  75.     char nazwaPliku[80];
  76.     snprintf(nazwaPliku, 80, "./MATEUSZ%d", argptr->numWatku);
  77.     FILE *fp = fopen(nazwaPliku, "w");
  78.     while(1)
  79.     {
  80.         if(argptr->numWatku==1) sem_wait(&rd1);
  81.         if(argptr->numWatku==2) sem_wait(&rd2);
  82.         if(argptr->numWatku==3) sem_wait(&rd3);
  83.             if(koniecPliku)
  84.             {
  85.                 fflush(fp);
  86.                 fclose(fp);
  87.                 pthread_exit(0);
  88.             }
  89.             fwrite(common, sizeof(char), strlen(common), fp);
  90.             printf("%d-%s\n", argptr->numWatku, common);
  91.             fflush(stdout);
  92.         if(argptr->numWatku==1) sem_post(&rd2);
  93.         if(argptr->numWatku==2) sem_post(&rd3);
  94.         if(argptr->numWatku==3) sem_post(&wr);
  95.     }
  96. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement