📄 操作系统课程设计读者写者问题源程序.txt
字号:
/*
Reader-Writer problem
Class:0504
NO.:0120510340412
Name:Song Yuanlin
Year.Month:2008.6
*/
#include<stdio.h>
#include<pthread.h>
#include<semaphore.h>
#include<stdlib.h>
void *reader(void *args);
void *writer(void *args);
pthread_mutex_t mutex;
sem_t wrt;
int count=0;
int share[20];
time_t end; //define the thread running time
int position1=0; //define the writer's position
int position2=0; //define the reader's position
/*main function*/
int main(int argc,char **argv)
{ end=time(NULL)+5;
pthread_mutex_init(&mutex,NULL);
sem_init(&wrt,0,1);
pthread_t r1,r2,r3,r4,w1,w2,w3;
int res;
/*create the thread for every reader and writer*/
res=pthread_create(&w1,NULL,(void*)writer,"Writer1");
res=pthread_create(&r1,NULL,(void*)reader,"Reader1");
res=pthread_create(&w2,NULL,(void*)writer,"Writer2");
res=pthread_create(&r2,NULL,(void*)reader,"Reader2");
res=pthread_create(&r3,NULL,(void*)reader,"Reader3");
res=pthread_create(&w3,NULL,(void*)writer,"writer3");
res=pthread_create(&r4,NULL,(void*)reader,"Reader4");
res=pthread_join(w1,NULL);
res=pthread_join(r1,NULL);
res=pthread_join(w2,NULL);
res=pthread_join(r2,NULL);
res=pthread_join(r3,NULL);
res=pthread_join(w3,NULL);
res=pthread_join(r4,NULL);
return 0;
}
/*reader thread function*/
void *reader(void *args)
{ int i;
while(time(NULL)<end)
{ pthread_mutex_lock(&mutex);
count++;
if(count==1)
sem_wait(&wrt);
pthread_mutex_unlock(&mutex);
if(position2<position1)
position2++;
else
position2=1;
printf(" %s is reading %d The current position is %d\n",(char*)args,position2,position2);
//display the reader's number and the current pointer
printf("------------------------The current content of the sharearea----------------------\n");
for(i=0;i<20;i++)
{
printf("| %d |",share[i]);
}
printf("\n=================================================================================\n\n");
pthread_mutex_lock(&mutex);
count--;
if(count==0)
sem_post(&wrt);
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
/*writer thread function*/
void *writer(void *args)
{ int i;
while(time(NULL)<end)
{
sem_wait(&wrt);
if(position1<20)
{
share[position1]=position1+1;
position1++;
printf("%s is writing %d The current position is %d\n",(char*)args,position1,position1);
//display the writer's number and the current pointer
printf("----------------The current content of the sharearea-----------------\n");
for(i=0;i<20;i++)
{
printf("| %d |",share[i]); //display the current of the sharearea
}
printf("\n====================================================================\n\n");
sem_post(&wrt);
sleep(3);
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -