Я написал простое решение проблемы Reader-Writer, используя семафоры на C. Но я получаю разные результаты после каждого успешного запуска.Какова точная причина этого?Вот код:
#include<stdio.h>
#include<semaphore.h>
#include<pthread.h>
#include<string.h>
sem_t x,wsem;
int rc;
void *reader(void *);
void *writer(void *);
int svar=0;
int main()
{
pthread_t w[2],r[3];
sem_init(&x,0,1);
sem_init(&wsem,0,1);
rc=0;
pthread_create(&w[0],NULL,writer,(void *)0);
pthread_create(&r[0],NULL,reader,(void *)0);
pthread_create(&w[1],NULL,writer,(void *)1);
pthread_create(&r[1],NULL,reader,(void *)1);
pthread_create(&r[2],NULL,reader,(void *)2);
pthread_join(r[0],NULL);
pthread_join(w[0],NULL);
pthread_join(w[1],NULL);
pthread_join(r[1],NULL);
pthread_join(r[2],NULL);
sem_destroy(&x);
sem_destroy(&wsem);
return 0;
}
void *reader(void *arg)
{
printf("\nReader is executing......");
sem_wait(&x);
rc++;
if (rc == 1)
sem_wait(&wsem);
sem_post(&x);
printf("Reader-%d : value of shared variable : %d\n", (int)arg,svar);
sem_wait(&x);
rc--;
if (rc==0)
sem_post(&wsem);
sem_post(&x);
}
void *writer(void *arg)
{
printf("\nWriter is executing......");
sem_wait(&wsem);
svar=svar+5;
printf("Writer-%d : value of shared variable : %d\n",(int)arg,svar);
sem_post(&wsem);
}
Output1 :
Writer is executing......Writer-0 : value of shared variable : 5
Reader is executing......Reader-0 : value of shared variable : 5
Reader is executing......Reader-1 : value of shared variable : 5
Writer is executing......Writer-1 : value of shared variable : 10
Reader is executing......Reader-2 : value of shared variable : 10
Output2:
Writer is executing......Writer-0 : value of shared variable : 5
Writer is executing......Writer-1 : value of shared variable : 10
Reader is executing......Reader-1 : value of shared variable : 10
Reader is executing......Reader-0 : value of shared variable : 10
Reader is executing......Reader-2 : value of shared variable : 10
Output3:
Writer is executing......Writer-0 : value of shared variable : 5
Writer is executing......Writer-1 : value of shared variable : 10
Reader is executing......Reader-1 : value of shared variable : 10
Reader is executing......Reader-0 : value of shared variable : 10
Reader is executing......Reader-2 : value of shared variable : 10