Witam,
Zagłębiłem się w problem czytający-piszący z priorytetem dla czytających. Czy taki kod jest poprawny dla 20 procesów ?
#include<stdio.h>
#include<pthread.h>
#include<semaphore.h>
sem_t mutex,writeblock;
int data = 0,rcount = 0;
void *reader(void *arg)
{
int f;
f = ((int)arg);
sem_wait(&mutex);
rcount = rcount + 1;
if(rcount==1)
sem_wait(&writeblock);
sem_post(&mutex);
printf("Proces wczytany przez czytajacego %d to %d\n",f,data);
sleep(1);
sem_wait(&mutex);
rcount = rcount - 1;
if(rcount==0)
sem_post(&writeblock);
sem_post(&mutex);
}
void *writer(void *arg)
{
int f;
f = ((int) arg);
sem_wait(&writeblock);
data++;
printf("Proces napisany przez piszacego %d to %d\n",f,data);
sleep(1);
sem_post(&writeblock);
}
main()
{
int i,b;
pthread_t rtid[20],wtid[20];
sem_init(&mutex,0,1);
sem_init(&writeblock,0,19);
for(i=0;i<=20;i++)
{
pthread_create(&wtid[i],NULL,writer,(void *)i);
pthread_create(&rtid[i],NULL,reader,(void *)i);
}
for(i=0;i<=20;i++)
{
pthread_join(wtid[i],NULL);
pthread_join(rtid[i],NULL);
}