自己编的糟糕系统,大家帮忙看一下吧!
问题:通过研究线程机制和信号量实现读者阅览问题(Reading-Reader Probelem)的并发控制。
设阅览室有5把椅子,几把椅子可用连续存储单元。
1.2技术要求:
1) 每个读者进入阅览室后,即时显示“Entered” 及其线程自定义标识,还同时显示阅览室共有几名顾客及其所坐的位置。
2) 至少有10个读者,每人阅览至少3秒钟。
3) 多个读者须共享操作函数代码。
2.1设计思想
1) 每个读者进入阅览室后,即时显示“Entered” 及其线程自定义标识,还同时显示阅览室共有几名顾客及其所坐的位置。
2) 至少有10个读者,每人阅览至少3秒钟。
以下是本人编写的代码,我是初学者,错误很多,希望各位高手指点一下如何改正,万分的感谢!
#include<stdio.h>
#include<math.h>
#include<process.h>
#include<stdlib.h>
#include<windows.h>
#include<time.h>
unsigned long Reader[10];
long mutex;
long empty;
int count=0;
int readerStack[6];
int enter()
{
int i;
for(i=1;i<6;i++)
{
if(0==readerStack[i])
return i;
}
return 0;
}
void * read(void *arg)
{
int index,t,i;
t=rand()%20+3;
CreateSemaphore(NULL,empty,6,NULL);
printf(">>The %dth pthread enter\n",arg);
index=enter();
readerStack[index]=(int)arg;
CreateSemaphore(NULL,mutex,6,NULL);
count++;
printf("Total pthread numbers :%d\n",count);
printf("The %dth pthread will sit on %dth seat read for %d s. \n",arg,index,t);
printf("Location:");
for(i=1;i<6;i++)
printf("%d,",readerStack[i]);
printf("\n");
printf(">>>>Waiting reader:");
for(i=(int)arg;i<10;i++)
printf("%d,",i+1);
printf("\n");
ReleaseSemaphore(&mutex,6,NULL);
clock_t clock( void );
ReleaseSemaphore(&empty,6,NULL);
CreateSemaphore(NULL,mutex,6,NULL);
count--;
for(i=1;i<6;i++)
{
if((int)arg==readerStack[i])
{
readerStack[i]=0;
break;
}
}
printf("<<The %dth reader is leaving reading room\n",arg);
printf("Total pthread numbers %d\n",count);
printf("Location:");
for(i=1;i<6;i++)
printf("%d,",readerStack[i]);
printf("\n");
ReleaseSemaphore(&mutex,6,NULL);
}
int main()
{
CreateSemaphore(NULL,mutex,0,NULL);
CreateSemaphore(NULL,empty,0,NULL);
int i;
unsigned long ThreadProc();
for(i=0;i<6;i++)
readerStack[i]=0;
for(i=0;i<10;i++)
unsigned _beginthread( &Reader[i],0, NULL);
for(i=0;i<10;i++)
WaitForMultipleObjects(i,NULL,NULL,3);
return 0;
}