【问题标题】:Cyclic queue with full BUFFER capacity满 BUFFER 容量的循环队列
【发布时间】:2021-09-29 01:41:16
【问题描述】:
#define BUFFER_SIZE 10
typedef {
...
} item;

item buffer[BUFFER_SIZE];
int in = 0;
int out = 0;

当缓冲区为空时

in == out

缓冲区满时

((in+1)%BUFFER_SIZE) == out

该算法最多允许BUFFER_SIZE - 1 项同时在缓冲区中。

有没有解决方案,BUFFER_SIZE 项可以同时在缓冲区中?

【问题讨论】:

    标签: arrays c algorithm queue


    【解决方案1】:

    使用一个整数变量 counter,初始化为 0。每次我们向缓冲区添加新项目时,计数器都会增加,每次从缓冲区中删除一项时,计数器就会减少。

    制片人-

    while (true) {
      /* produce an item in nextProduced */ 
      while (counter == BUFFER_SIZE)
      ; /* do nothing */ 
      buffer[in] = nextProduced; 
      in = (in + 1) %BUFFER_SIZE; 
      counter++;
    }
    

    消费者 -

    while (true) {
      while (counter == 0)
      ; /* do nothing */
      nextConsumed = buffer[out];
      out = (out + 1) % BUFFER_SIZE; 
      counter--;
      /* consume the item in nextConsumed */
    }
    
    

    【讨论】:

      猜你喜欢
      • 2014-11-14
      • 1970-01-01
      • 1970-01-01
      • 2012-07-06
      • 1970-01-01
      • 2012-08-05
      • 2014-01-05
      • 2013-02-01
      • 2014-01-04
      相关资源
      最近更新 更多