我正在编写一个模拟“读者-作家”问题的程序。为什么当我启动一个有10个读者和10个作家的程序时,在阅览室只能输入1个读者。我的错误在哪里?
int READERS;
int READERS_WORKING = 0;
int WRITERS;
int WRITERS_WORKING = 0;
sem_t resource, reader;
void PrintStatus(){
printf("Outside: %d readers and %d writers, Inside: %d readers and %d writers\n", (READERS-READERS_WORKING), (WRITERS-WRITERS_WORKING), READERS_WORKING, WRITERS_WORKING);
}
void *readersWork(void *arg) {
while (1) {
sem_wait(&reader);
READERS_WORKING++;
if (READERS_WORKING == 1) {
sem_wait(&resource);
}
PrintStatus();
sem_post(&reader);
sleep(2); //Working
sem_wait(&reader);
READERS_WORKING--;
if (READERS_WORKING == 0) { // Last reader inside
sem_post(&resource);
}
sem_post(&reader);
PrintStatus();
}
return 0;
}
void *writersWork(void *arg) {
while (1) {
sem_wait(&resource);
PrintStatus();
WRITERS_WORKING++;
sleep(2);
sem_post(&resource);
WRITERS_WORKING--;
//PrintStatus();
}
return 0;
}