我想请求帮助完成这项任务。
我的任务是用C语言编写一个简单的程序来模拟读者和作者的问题。项目要求如下:
程序启动后,将要求用户输入写入程序和读取程序的计数。
程序将不断地通知用户线程的状态。
程序结束后,几乎没有统计(每个读者读了多少遍,每个作家写了多少遍)。
我已经完成了程序的一些基本结构(通过信号量处理关键部分等),但我认为程序不做,它应该做什么。程序运行时没有错误或意外行为,但计数、每个读写器读多少次和每个写写写器写多少次始终是每个读写器一次)。
我错在哪里?也许我不太理解这项任务。
非常感谢您的回复。
程序代码:
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
sem_t w; // write access
sem_t m; // mutex
int rc=0; // readers count
int writersCount;
int readersCount;
pthread_t writersThread[10], readersThread[10];
int writeCount[10], readCount[10];
int i;
void *writer(void *i) {
int a = *((int *) i);
sem_wait(&w); // P(w)
printf("Writer %d writes to DB.\n",a+1);
writeCount[a+1]++;
sem_post(&w); // V(w)
free(i);
}
void *reader(void *i) {
int a = *((int *) i);
sem_wait(&m); // P(m)
rc++;
if (rc == 1) {
sem_wait(&w); // P(w)
}
sem_post(&m); // V (m)
printf("Reader %d reads from DB.\n",a+1);
readCount[a+1]++;
sem_wait(&m); // P(m)
rc--;
if (rc == 0) {
sem_post(&w); // V(w)
}
sem_post(&m); // V(m)
free(i);
}
int main() {
sem_init(&w,0,1);
sem_init(&m,0,1);
printf("Enter count of writers:");
scanf("%d",&writersCount);
printf("Enter count of readers:");
scanf("%d",&readersCount);
for (i=0; i<readersCount; i++) {
int *arg = malloc(sizeof(*arg));
*arg = i;
pthread_create(&readersThread[i], NULL, reader, arg);
}
for (i=0; i<writersCount; i++) {
int *arg = malloc(sizeof(*arg));
*arg = i;
pthread_create(&writersThread[i], NULL, writer, arg);
}
for (i=0; i<writersCount; i++) {
pthread_join(writersThread[i], NULL);
}
for (i=0; i<readersCount; i++) {
pthread_join(readersThread[i], NULL);
}
printf("--------------\n");
for (i=0; i<readersCount; i++) {
printf("Reader %d read %d times\n",i+1,readCount[i+1]);
}
for (i=0; i<writersCount; i++) {
printf("Writer %d wrote %d times\n",i+1,writeCount[i+1]);
}
sem_destroy(&w);
sem_destroy(&m);
return 0;
}
输出:
输入写入数:4
输入读卡器数量:4
Reader 1 reads from DB.
Reader 3 reads from DB.
Reader 4 reads from DB.
Reader 2 reads from DB.
Writer 1 writes to DB.
Writer 2 writes to DB.
Writer 3 writes to DB.
Writer 4 writes to DB.
--------------
Reader 1 read 1 times
Reader 2 read 1 times
Reader 3 read 1 times
Reader 4 read 1 times
Writer 1 wrote 1 times
Writer 2 wrote 1 times
Writer 3 wrote 1 times
Writer 4 wrote 1 times
最佳答案
您的输出是完全正确的,因为您运行的每个线程只执行一次读/写操作。在reader/writer函数中放一些循环来改变这个事实。您的程序在与10个读卡器或写卡器一起运行时可能会遇到错误,因为其中一个读卡器或写卡器将尝试访问writeCount[10]
或readCount[10]
,更改该读卡器或写卡器,您就拥有了正确的程序。