/*
* 读者写者问题,读者写者是否公平竞争,读优先写优先不同
* 读者之间不互斥,可以多个读操作同时进行
* 读操作和写操作不可以同时进行(R-W,互斥)
* 写操作和写操作不可以同时进行(W-W,互斥)
* 在实际应用中,写优先非常重要,因为写代表的是对数据的更新。
* 而我们希望读到的是最新的消息。因此继续进行改进,就要考虑,
* 如果写者到来,可以让正在读的读者让路,先让写者写。
* 要求实现的是读者写者公平
*/
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#define N 20
int readcount=0,writecount=0;
sem_t s,w;// 同步信号量
pthread_mutex_t mutex,wmutex;
void *writer(void *a)//读者写者公平
{
while(1)
{
sleep(1);
pthread_mutex_lock(&wmutex);//P(wmutex);
writecount++;
if(writecount==1)
sem_wait(&s);//P(S);
pthread_mutex_unlock(&wmutex);//V(wmutex);
sem_wait(&w);//P(w);
printf("Writing is writing\n");//写
sleep(1);
sem_post(&w);//V(w);
pthread_mutex_lock(&wmutex);//P(wmutex);
writecount--;
if(writecount==0)
sem_post(&s);//V(S);
pthread_mutex_unlock(&wmutex);//V(wmutex);
}
}
void *reader(void *a)//读者写者公平
{
while(1)
{
sleep(1);
sem_wait(&s);//P(S);
pthread_mutex_lock(&mutex); //给互斥体变量加锁//P(mutex);
readcount ++;
if(readcount==1)
sem_wait(&w);//P (w);
pthread_mutex_unlock(&mutex);//V(mutex);
sem_post(&s); //V(S);
printf("Reader is reading\n");//读
sleep(1);
pthread_mutex_lock(&mutex); //P(mutex);
readcount --;
if(readcount==0)
sem_post(&w);//V(w);
pthread_mutex_unlock(&mutex);//V(mutex);
}
}
int main()
{
int i;
int ret[N];
// 初始化同步信号量
int ini1 = sem_init(&s, 0, 1);//函数sem_init()用来初始化一个信号量
int ini2 = sem_init(&w, 0, 1);
if(ini1!=0 ||ini2 != 0)
{
printf("sem init failed \n");
exit(1);
}
//初始化互斥信号量
int ini3 = pthread_mutex_init(&mutex, NULL);
int ini4 = pthread_mutex_init(&wmutex, NULL);
if(ini3 !=0 ||ini4!=0)
{
printf("mutex init failed \n");
exit(1);
}
pthread_t id1[N];
pthread_t id2[N];
for(i = 0; i < 10; i++)
{
pthread_create(&id2[i], NULL, reader, NULL);
}
for(i = 0; i < 5; i++)
{
ret[i] = pthread_create(&id1[i], NULL, writer, (void *)(&i));
if(ret[i] != 0)
{
printf("product%d creation failed \n", i);
exit(1);
}
}
for(i = 10; i < 20; i++)
{
ret[i] = pthread_create(&id2[i], NULL, reader, NULL);
if(ret[i] != 0)
{
printf("prochase%d creation failed \n", i);
exit(1);
}
}
for(i = 5; i < 10; i++)
{
ret[i] = pthread_create(&id1[i], NULL, writer, (void *)(&i));
if(ret[i] != 0)
{
printf("product%d creation failed \n", i);
exit(1);
}
}
for(i = 0; i < N; i++)//销毁线程
{
pthread_join(id1[i],NULL);
pthread_join(id2[i],NULL);
}
exit(0);//还是完全没搞清楚多线程怎么在运行,郁闷
//执行结果有问题,不过助教还是让过了,并讲解一番,赞一个 :)
}
操作系统—读者写者问题
最新推荐文章于 2023-12-10 21:12:41 发布