資源簡介
熟練應用生產者消費者PV操作的實驗,
實驗內容
1. 由用戶指定要產生的進程及其類別,存入進入就緒隊列。
2. 調度程序從就緒隊列中提取一個就緒進程運行。如果申請的資源被阻塞則進入相應的等待隊列,調度程序調度就緒隊列中的下一個進程。進程運行結束時,會檢查對應的等待隊列,激活隊列中的進程進入就緒隊列。運行結束的進程進入over鏈表。重復這一過程直至就緒隊列為空。
3. 程序詢問是否要繼續?如果要轉直①開始執行,否則退出程序。
代碼片段和文件信息
#include?“stdio.h“
#include??
#include??
#include?“iostream.h“
#define?NULL?0?
#define?OK?1
#define?ERROR?0
#define?buffersize?3
#define?getpch(type)?(type*)malloc(sizeof(type))?
int?productnum=0;??//產品數量
int?processnum=0;//進程計數器
int?full=0;?
int?empty=buffersize;?//?semaphore
char?buffer[buffersize];??//?緩沖區
int?bufferpoint=0;??//?緩沖區指針
struct?pcb?
{??/*?定義進程控制塊PCB?*/
int?flag;??//?flag=1?表示生產者;?flag=2?表示消費者
int?numlabel;//進程編號
char?product;//產品
char?state;//進程狀態
struct?pcb?*?processlink;
}*exe=NULL*over=NULL;??//?over鏈表
typedef?struct?pcb?PCB;
PCB*?readyhead=NULL?*?readytail=NULL;???//?就緒隊列
PCB*?consumerhead=NULL?*?consumertail=NULL;??//?消費者隊列
PCB*?producerhead=NULL?*?producertail=NULL;???//?生產者隊列
int?InitQueue?(PCB*?headPCB*?tail)
{//初始化隊列
????if(!head)?
exit(0);
????head->processlink=NULL;
????return?OK;
}
bool?hasElement(PCB*pro)
{//判斷隊列是否為空
if(pro->processlink==NULL)
return?false;
else?
return?true;
}
void?linkqueue(PCB*?processPCB**?tail)
{???//?把就緒隊列里的進程放入生產者隊列的尾
(*tail)->processlink=process;
(*tail)=process;?
return?;
}
void?freelink(PCB*?linkhead)
{//清除隊列
PCB*?p;
while(linkhead!=NULL)
{
p=linkhead;
linkhead=linkhead->processlink;
free(p);
}
return?;
}
PCB*?getq(PCB*?headPCB**?tail)
{//出隊
PCB*?p;
p=head->processlink;
if(p!=NULL)
{
head->processlink=p->processlink;
p->processlink=NULL;?
if(?head->processlink?==NULL?)
(*tail)=head;
}
else
return?NULL;
return?p;
}
void?linklist(PCB*?pPCB*?listhead)
{
PCB*?cursor=listhead;
while(cursor->processlink!=NULL)
{
cursor=cursor->processlink;
}
cursor->processlink=p;
}
int?processproc()
{//給PCB分配內存。
int?ifnum;
char?ch;
PCB*p=NULL;
cout< printf(“:)??請輸入進程個數:“);
cin>>num;
for(i=0;i {//產生相應的的進程:
cout<<“:)??輸入1生產者進程“< cout<<“:)??輸入2消費者進程“< scanf(“%d“&f);????????????????????????????
getchar();
p=(PCB*)malloc(sizeof(PCB));
if(!p)
{
cout<<“:)??內存分配失敗“< return?false;
}
p->flag=f;//進程標志,1為生產者,2為消費者
processnum++;//進程計數器加1
p->numlabel=processnum;//進程編號記為進程計數器
p->state=‘w‘;//置為等待
p->processlink=NULL;
if(p->flag==1)
{//輸入1為生產者進程;
cout<<“:)??您要產生的進程是生產者,它是第“< cout<<“:)??請輸入您要該進程產生的字符“< scanf(“%c“&ch);
getchar();
p->product=ch;
productnum++;
cout<<“:)??該進程產生的內容是“<product< }
else
{?//輸入2為消費者進程;
cout<<“:)??產生的進程是消費者,它是第“<numlabel<<“個進程“< }
linkqueue(p&readytail);??//并把這些進程放入就緒隊列中。
}
return?true;
}
bool?waitempty()
{//?如果緩沖區滿,該進程進入生產者等待隊列;
if(empty<=0)
{
cout<<“:)??進程“<numlabel<<“緩沖區存數,該進程進入生產者等待隊列“< linkqueue(exe&producertail);//緩沖區滿,進程壓入生產者等待隊列隊尾
return?false;
}
else
{
empty--;//緩沖區未滿,則進行生產操作
return?true;
}
}
void?signalempty()
{//將等待中的生產者進程進入就緒隊列
PCB*?p;
- 上一篇:C語言socket編程實現網絡數據傳輸
- 下一篇:C++模糊邏輯代碼實現
評論
共有 條評論