操作系统模拟生产者消费者问题

pv操作及生产者消费者问题解析

#include
#include
#include
#include
#include

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);
  }
}

你可能感兴趣的:(操作系统,生产者消费者问题)