问题描述
代码:
#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;
}
运行截图