#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <semaphore.h>
#define P sem_wait
#define V sem_post
sem_t rmutex, wmutex; //读者互斥,写者互斥
sem_t S; //S在写着到达后封锁读者
int readcount=0; //记录当前读者数目
struct data //创建一个结构体,表示进程的id,等待运行时间,进程持续时间
{
int id;
int operatingTime;
int lastingTime;
};
void * reader(void *param)
{
int id=((struct data*)param)->id; //传参
int operatingTime=((struct data*)param)->operatingTime;
int lastingTime=((struct data*)param)->lastingTime;
sleep(operatingTime);
printf("Thread %d: waiting to read\n",id); //等候阅读
P(&S);
P(&rmutex);
readcount++;
if(readcount==1)
P(&wmutex);
V(&rmutex);
V(&S);
printf("Thread %d: start to read\n",id);
sleep(lastingTime); //正在阅读中
printf("Thread %d: end reading\n",id);
P(&rmutex);
readcount--;
if(readcount==0)
V(&wmutex);
V(&rmutex);
pthread_exit(0);
}
void *writer(void *param)
{
int id=((struct data*)param)->id; //传参
int operatingTime=((struct data*)param)->operatingTime;
int lastingTime=((struct data*)param)->lastingTime;
sleep(operatingTime);
printf("Thread %d: waiting to write\n",id); //等候写
P(&S);
P(&wmutex);
printf("Thread %d: start to write\n",id);
sleep(lastingTime); //正在写文件中
printf("Thread %d: end write\n",id);
V(&wmutex);
V(&S);
pthread_exit(0);
}
int main()
{
sem_init(&S,0,1);
sem_init(&rmutex,0,1);
sem_init(&wmutex,0,1);
pthread_t tid; //线程id
int id=0;
while (scanf("%d",&id)!=EOF) //当输入的id不为文件结束符时,一直读取,直到输入缓存中的内容为空时停止
{
char role; //是读者还是写者
int operatingTime;
int lastingTime;
scanf("%c%d%d",&role,&operatingTime,&lastingTime);
struct data*d=(struct data*)malloc(sizeof(struct data)); //结构体指针,指针调用。需要人为分配空间、释放空间、初始化
d->id=id;
d->operatingTime=operatingTime;
d->lastingTime=lastingTime;
if(role == 'r'){
printf("Creat the %d thread: Reader\n",id);
pthread_create(&tid,NULL,reader,d);
}
else if(role == 'w'){
printf("Creat the %d thread: Writer\n",id);
pthread_create(&tid,NULL,writer,d);
}
}
sem_destroy(&S);
sem_destroy(&rmutex);
sem_destroy(&wmutex);
return 0;
}
C Linux 读者写者(相对公平)
最新推荐文章于 2021-05-13 07:51:57 发布