资源描述:
《操作系统生产者消费者问题C语言.doc》由会员上传分享,免费在线阅读,更多相关内容在学术论文-天天文库。
1、《操作系统概念》第七版中的实验项目:生产者消费者问题。本程序中,main()函数需要三个参数:主线程休眠时间;生产者线程数;消费者线程数。各线程的休眠等待时间是随机的。程序代码:#include#include#include#include#defineBUFFER_SIZE5typedefintbuffer_item;structv{inti;};buffer_itembuffer[BUFFER_SIZE+1];buffer_itemfront=0,rear=0;HANDLEmutex,empty,full;i
2、ntinsert_item(buffer_itemitem){/*insertitemintobufferreturn0ifsuccessful,otherwisereturn-1indicatinganerrorcondition*/if((rear+1)%(BUFFER_SIZE+1)==front)return1;buffer[rear]=item;rear=(rear+1)%(BUFFER_SIZE+1);return0;}intremove_item(buffer_item*item){/*removeanobjectfrombufferplacingitinitemreturn
3、0ifsuccessful,otherwisereutrn-1indicationanerrorcondition*/if(front==rear)return1;*item=buffer[front];front=(front+1)%(BUFFER_SIZE+1);return0;}DWORDWINAPIproducer(PVOIDParam){intrand1;structvdata=*(structv*)Param;srand((unsigned)time(0));while(1){Sleep(rand()%101*10);WaitForSingleObject(empty,INFI
4、NITE);WaitForSingleObject(mutex,INFINITE);rand1=rand();printf("producerhasproducerd%dBy%d",rand1,data.i);if(insert_item(rand1))printf("insertdataerror!");ReleaseMutex(mutex);ReleaseSemaphore(full,1,NULL);}}DWORDWINAPIconsumer(PVOIDParam){intrand1;structvdata=*(structv*)Param;srand((unsigned)ti
5、me(0));while(1){Sleep(rand()%101*10);WaitForSingleObject(full,INFINITE);WaitForSingleObject(mutex,INFINITE);if(remove_item(&rand1))printf("removedataerror!");elseprintf("consumerconsumed%dBy%d",rand1,data.i);ReleaseMutex(mutex);ReleaseSemaphore(empty,1,NULL);}}intmain(intargc,char*argv[]){/*Ge
6、tcommandlineargumentsargv[1])(thenumberofproducerthreads),argv[2](thenumberofconsumerthreads),argv[3](sleeptime)*//*Initializebuffer*/intsleeptime,pnum,snum;int*ThreadIdP,*ThreadIdS,i;structv*countp,*counts;HANDLE*ThreadHandleP,*ThreadHandleS;sleeptime=atoi(argv[1]);pnum=atoi(argv[2]);snum=atoi(ar
7、gv[3]);/*srand(time(NULL));sleeptime=9000;pnum=3;snum=3;*/ThreadHandleP=(HANDLE*)malloc(pnum*sizeof(HANDLE));ThreadHandleS=(HANDLE*)malloc(snum*sizeof(HANDLE));ThreadIdP=(int*)malloc(pnum*sizeof(int));ThreadIdS=(