V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
sbldehanhan
V2EX  ›  C++

生产者消费者小白问题!

  •  
  •   sbldehanhan · 251 天前 · 1404 次点击
    这是一个创建于 251 天前的主题,其中的信息可能已经有所发展或是发生改变。

    (ir->not_full).wait(lock);为啥要把这句 baok 包含到 while 循环里?直接等着不满的信号不就好了? while 也是判断不满的呀?

    void Producer(resource *ir, int item)
    {
    	std::unique_lock<std::mutex> lock(ir->mtx);
    	while (((ir->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(); // 通知消费者产品库不为空.
    }
    
    6 条回复    2023-08-25 12:22:51 +08:00
    anjingdexiaocai
        1
    anjingdexiaocai  
       251 天前 via Android
    搜索一下 竞态条件( Race Condition )
    mmdsun
        2
    mmdsun  
       251 天前
    虚假唤醒? Spurious wakeup
    dangyuluo
        3
    dangyuluo  
       250 天前
    似乎是在处理 spurious wakeup ,不过 condition variable 本身就可以接受 predictor ,不知道这么做的意义是什么。看样子会有多个 Producer
    sbldehanhan
        4
    sbldehanhan  
    OP
       250 天前
    @dangyuluo #3 是有多个生产者。是说可能其他生产者可能已经在生产了?
    dangyuluo
        5
    dangyuluo  
       250 天前
    肯定要考虑竞争的呀,不过这种设计感觉怪怪的
    dangyuluo
        6
    dangyuluo  
       250 天前
    估计 consumer 消费的时候用的是 ir->not_full.notify_all(),然后多个 producer 为了不超出 buffer 大小,只能用这个方法了。设计有点问题
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1042 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 18:23 · PVG 02:23 · LAX 11:23 · JFK 14:23
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.