作業系統模擬生產者消費者問題
阿新 • • 發佈:2019-01-25
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<time.h>
#include<windows.h>
void procducer();
void consumer();
int buffer[10];//緩衝區
int count = 0;//生產的貨物數
int length = 10;//緩衝區大小
int main() {
memset(buffer, 0, sizeof(buffer));//初始化緩衝區為空
while(1) {
Sleep(500 );
srand(time(0));
int a = rand() % (21) + 10;//產生10到30的隨機數
if (a % 2) consumer();//隨機數為奇數執行
else procducer();//為偶數執行
//printf("%d\n", a);
}
}
void consumer() {
if (count > 0) {
for (int i = 0; i < length; i++) {
if (buffer[i] == 1) {
buffer[i] = 0;
count--;
printf ("\n消費者消費一個產品,還剩%d個產品\n", count);
break;
}
}
}else {
printf("\n緩衝區產品為空\n");
}
}
void procducer() {
int i;
int judge = 0;
for (i = 0; i < length; i++) {
if (buffer[i] == 0) {
judge = 1;
break;
}
}
if (judge == 0) printf("\n緩衝區已放滿10個產品\n");
if (judge == 1 ) {
buffer[i] = 1;
count++;
printf("\n生產者生產一個產品,還剩%d個產品\n", count);
}
}