Advertisement
rabbitekk312

Untitled

Feb 14th, 2021
560
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.87 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <sys/mman.h>
  4. #include <semaphore.h>
  5. #define ITERATION 2
  6.  
  7. int *readCount, *crit_sec;
  8. sem_t wrt, mutex, *s1, *s2;
  9.  
  10. void pisarz(int numPisarz)
  11. {
  12.     sem_wait(&wrt);
  13.     *crit_sec=rand()%100+1;
  14.     printf("Pisarz %d - Napisal: %d\n", numPisarz, *crit_sec);
  15.     sem_post(&wrt);
  16.     return;
  17. }
  18.  
  19. void czytelnik(int numCzytelnik)
  20. {
  21.     sem_wait(&mutex);
  22.     *readCount++;
  23.     if(*readCount==1) sem_wait(&wrt);
  24.     sem_post(&mutex);
  25.     printf("Czytelnik %d - Przeczytal: %d\n", numCzytelnik, *crit_sec);
  26.     sem_wait(&mutex);
  27.     *readCount--;
  28.     if(*readCount==0) sem_post(&wrt);
  29.     sem_post(&mutex);
  30.     return;
  31. }
  32.  
  33. int main(int argv, char **argc)
  34. {
  35.     int numCzyt, numPis;
  36.     void *ptr1=mmap(NULL, 2*sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, 0, 0);
  37.     void *ptr2=mmap(NULL, 2*sizeof(sem_t), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, 0, 0);
  38.     crit_sec=ptr1, readCount=ptr1+1;
  39.     *crit_sec=0, *readCount=0;
  40.     s1=ptr2, s2=ptr2+1;
  41.     *s1=mutex, *s2=wrt;
  42.     sem_init(&mutex,1,1);
  43.     sem_init(&wrt,1,1);
  44.     if(argv!=3)
  45.     {
  46.         printf("Niepoprawne uzycie - nalezy ./CzytPis [czytelnicy] [pisarze]\n");
  47.         return 0;
  48.     }
  49.     if(sscanf(argc[1], "%i", &numCzyt)!=1|| sscanf (argc[2], "%i", &numPis)!=1)
  50.     {
  51.         printf("Niepoprawne uzycie - nalezy ./CzytPis [czytelnicy] [pisarze]\n");
  52.         return 0;
  53.     }
  54.     int rcnt=0;
  55.     while(rcnt++<numCzyt)
  56.     {
  57.         if(fork()==0)
  58.         {
  59.                 int i=0;        
  60.                 for(;i<ITERATION;i++) czytelnik(rcnt);
  61.                 return;
  62.         }
  63.     }
  64.     int wcnt=0;
  65.     while(wcnt++<numPis)
  66.     {
  67.         if (fork()==0)
  68.         {
  69.                 int j=0;
  70.                 for(;j<ITERATION;j++) pisarz(wcnt);
  71.                 return;  
  72.         }
  73.     }
  74.     return 0;
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement