Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <sys/mman.h>
- #include <semaphore.h>
- #define ITERATION 2
- int *readCount, *crit_sec;
- sem_t wrt, mutex, *s1, *s2;
- void pisarz(int numPisarz)
- {
- sem_wait(&wrt);
- *crit_sec=rand()%100+1;
- printf("Pisarz %d - Napisal: %d\n", numPisarz, *crit_sec);
- sem_post(&wrt);
- return;
- }
- void czytelnik(int numCzytelnik)
- {
- sem_wait(&mutex);
- *readCount++;
- if(*readCount==1) sem_wait(&wrt);
- sem_post(&mutex);
- printf("Czytelnik %d - Przeczytal: %d\n", numCzytelnik, *crit_sec);
- sem_wait(&mutex);
- *readCount--;
- if(*readCount==0) sem_post(&wrt);
- sem_post(&mutex);
- return;
- }
- int main(int argv, char **argc)
- {
- int numCzyt, numPis;
- void *ptr1=mmap(NULL, 2*sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, 0, 0);
- void *ptr2=mmap(NULL, 2*sizeof(sem_t), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, 0, 0);
- crit_sec=ptr1, readCount=ptr1+1;
- *crit_sec=0, *readCount=0;
- s1=ptr2, s2=ptr2+1;
- *s1=mutex, *s2=wrt;
- sem_init(&mutex,1,1);
- sem_init(&wrt,1,1);
- if(argv!=3)
- {
- printf("Niepoprawne uzycie - nalezy ./CzytPis [czytelnicy] [pisarze]\n");
- return 0;
- }
- if(sscanf(argc[1], "%i", &numCzyt)!=1|| sscanf (argc[2], "%i", &numPis)!=1)
- {
- printf("Niepoprawne uzycie - nalezy ./CzytPis [czytelnicy] [pisarze]\n");
- return 0;
- }
- int rcnt=0;
- while(rcnt++<numCzyt)
- {
- if(fork()==0)
- {
- int i=0;
- for(;i<ITERATION;i++) czytelnik(rcnt);
- return;
- }
- }
- int wcnt=0;
- while(wcnt++<numPis)
- {
- if (fork()==0)
- {
- int j=0;
- for(;j<ITERATION;j++) pisarz(wcnt);
- return;
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement