資源簡介
參考教材中的生產者消費者算法,創建5個進程,其中兩個進程為生產者進程,3個進程為消費者進程。一個生產者進程試圖不斷地在一個緩沖中寫入大寫字母,另一個生產者進程試圖不斷地在緩沖中寫入小寫字母。3個消費者不斷地從緩沖中讀取一個字符并輸出。為了使得程序的輸出易于看到結果,仿照的實例程序,分別在生產者和消費者進程的合適的位置加入一些隨機睡眠時間。
代碼片段和文件信息
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define?N?1000
using?namespace?std;
int?buff;
int?fulll;
int?*full2;
char?*buff1;
void?plusORde(int?numint?number){
????full2[num]=full2[num]+number;
}
void?down(int?*num)
{
????while(true)
????{
????????if(*num>0)
????????{
????????????*num=*num-1;
????????????break;
????????}
????????sleep(1);
????}
}
void?up(int?*num)
{
????*num=*num+1;
}
char?produce_item_low()
{
????char?ch=((rand()?+7)%?26+97);
????return?ch;
}
char?produce_item_lar()
{
????char?ch=(rand()?%?26+65);
????return?ch?;
}
char?remove_item()
{
????char?ch=buff1[full2[1]-1];
buff1[full2[1]-1]=‘\0‘;
????down(&full2[1]);
????return?ch;
}
void?printfCharArray(char?*chararrayint?len){
????printf(“?flag:?%d??len:?%d?\n“full2[4]len);
}
void?insert_item(char?x)
{
????char?xx[2];
????xx[0]=x;
????xx[1]=‘\0‘;
????strcat(buff1xx);
????????up(&full2[1]);
}
void?consume_item(char?item)
{
????printf(“\n?remove:%c?“item);
????printfCharArray(buff1full2[1]);
}
void?producer(int?flag)
{
char?item;
while?(true)
{
???????????if(full2[4]>200)sleep(
評論
共有 條評論