【问题标题】:Condition variable notification and wait条件变量通知和等待
【发布时间】:2021-08-04 01:00:07
【问题描述】:

我正在查看代码https://www.cse.iitd.ernet.in/~sbansal/os/lec/l25.html 而且我无法理解 Consumer 和 producer 中的等待和通知顺序。 not_full 和 not_empty 条件变量的顺序是否正确?在生产者中,它应该等待 not_full 并通知 not_empty,而在消费者中,它应该等待 not_empty 并通知 notfull。我的理解正确吗?

int head = 0, tail = 0; 
struct cv not_full, not_empty;
struct lock qlock;

void produce(char data) {
  acquire(&qlock);
   (while ((head + 1) % MAX  ==  tail)) {
    wait(&not_full, &qlock); 
  }
  queue[head] = data;
  head = (head + 1) % MAX;
  notify(&not_full); // Here it will notify the consumer to wake up and processes the data 
  release(&qlock);
}

char consume(void) {
  acquire(&qlock);
  while () {
    wait(&not_empty, &qlock); // consumer will wake up on event from Producer 
  }
  e = queue[tail];
  tail = (tail + 1) % MAX;
  notify(&not_empty);
  release(&qlock);
  return e;
}

【问题讨论】:

  • (while ((head + 1) % MAX == tail))while () 看起来不像 C++

标签: c++ concurrency


【解决方案1】:

not_full和not_empty条件变量的顺序是否正确?

不,看起来原始代码中存在拼写错误或错误,produce() 应在将数据放入队列时通知 not_emptyconsume() 应在接收时通知 not_full。即使在逻辑上 - 函数通知变量它自己等待也没有任何意义。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-10
    • 1970-01-01
    • 2015-07-01
    • 1970-01-01
    相关资源
    最近更新 更多