<操作系统>读者写者问题(公平竞争)C语言实现

问题描述
在这里插入图片描述
代码:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <semaphore.h>
sem_t rmutex,wmutex,s;
int count;
void *read_i(int a)
{ 
   printf("第%d号读者想读\n",a+1);
   sem_wait(&s);
   sem_wait(&rmutex);
   count++;
   if(count==1)
   sem_wait(&wmutex);
   sem_post(&rmutex);
   sem_post(&s);
   printf("第%d号读者开始读文章\n",a+1);
   sleep(1);
   printf("第%d号读者读完文章\n",a+1);
   sem_wait(&rmutex);
   count--;
   if(count==0)
   sem_post(&wmutex);
   sem_post(&rmutex);

}
void *write_j(int b)
{
    printf("第%d号写者想写\n",b+1);
    sem_wait(&s);
    sem_wait(&wmutex);
    printf("第%d号写者开始写文章\n",b+1);
    sleep(4);
    printf("第%d号写者写完文章\n",b+1);
    sem_post(&wmutex);
    sem_post(&s);

}
int main()
{
	int sg1,sg2,sg3;
	pthread_t writer[5],reader[5];
	sg1=sem_init(&rmutex,0,1);
	sg2=sem_init(&s,0,1);
        sg3=sem_init(&wmutex,0,1);
        count=0;
        int n=0;
            for(int i=0;i<=4;i++)
{   
        n=i;      
        pthread_create(&reader[i],NULL,(void *)read_i,n); 
        pthread_create(&writer[i],NULL,(void *)write_j,n);
        sleep(1);
}
  for(int j=0;j<=4;j++)
{           
        pthread_join(reader[j],NULL);
}
	
  for(int k=0;k<=4;k++)
{           
        pthread_join(writer[k],NULL);
}
        sleep(2);
	return 0;

}
   

运行截图
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值