
(ir->not_full).wait(lock);为啥要把这句 baok 包含到 while 循环里?直接等着不满的信号不就好了? while 也是判断不满的呀?
void Producer(resource *ir, int item) { std::unique_lock<std::mutex> lock(ir->mtx); while (((ir-&t;write_pos + 1) % bufSize) == ir->read_pos) { // item buffer is full, just wait here. std::cout << "Producer is waiting for an empty slot...\n"; (ir->not_full).wait(lock); // 生产者等待"产品库缓冲区不为满"这一条件发生. } (ir->buf)[ir->write_pos] = item; // 写入产品. (ir->write_pos)++; // 写入位置后移. if (ir->write_pos == bufSize) // 写入位置若是在队列最后则重新设置为初始位置. ir->write_pos = 0; (ir->not_empty).notify_all(); // 通知消费者产品库不为空. } 1 anjingdexiaocai 2023-08-24 18:20:58 +08:00 via Android 搜索一下 竞态条件( Race Condition ) |
2 mmdsun 2023-08-24 23:48:09 +08:00 虚假唤醒? Spurious wakeup |
3 dangyuluo 2023-08-25 04:53:00 +08:00 似乎是在处理 spurious wakeup ,不过 condition variable 本身就可以接受 predictor ,不知道这么做的意义是什么。看样子会有多个 Producer |
4 sbldehanhan OP @dangyuluo #3 是有多个生产者。是说可能其他生产者可能已经在生产了? |
5 dangyuluo 2023-08-25 12:21:10 +08:00 肯定要考虑竞争的呀,不过这种设计感觉怪怪的 |
6 dangyuluo 2023-08-25 12:22:51 +08:00 估计 consumer 消费的时候用的是 ir->not_full.notify_all(),然后多个 producer 为了不超出 buffer 大小,只能用这个方法了。设计有点问题 |