【问题标题】:boost::scoped_lock not working (for me)boost::scoped_lock 不起作用(对我来说)
【发布时间】:2015-10-09 17:57:55
【问题描述】:

我正在扩展一个代码库,看看下面从一个类中取出的代码sn-p。为了不让你感到困惑,我尽可能简单:

std::queue< boost::shared_ptr<const Item> > _container;
boost::mutex _mutex;
//...
void foo(Item *item)
{
    boost::mutex::scoped_lock lock(_mutex);
    std::cout << "enter " << _container.size() << "  " << this << std::endl;
    boost::shared_ptr<const Item> instr(item);
    _container.push( instr );

    // we only need to signal when size turns from 0 --> 1
    if (_container.size() == 1)
    {
        std::cout << "SIGNALLING" << "  " << this << std::endl;
        signal();//pop the _container until empty
    }
    else
    {
        std::cout <<"NOT SIGNALLING " << _container.size() << "  " << this << std::endl;
    }
}

我在标准输出中得到了这个:

enter 0  0xe919f0
enter 1  0xe919f0
NOT SIGNALLING 2  0xe919f0
enter 2  0xe919f0
NOT SIGNALLING 3  0xe919f0

....等等。 signal() 未被调用。我打印了this 以表明我们正在对同一个对象进行操作。

在何种情况下发生的可能性有多大? `'foo 最初被输入两次(并且与其余逻辑混淆),同时它受到互斥锁的保护!

感谢您的解决方案。 谢谢

【问题讨论】:

  • 在提供的代码中不可能发生这种情况。还有其他事情在起作用。

标签: c++ multithreading boost mutex scoped-lock


【解决方案1】:

在何种情况下发生的可能性有多大? `'foo 最初被输入两次(并且与其余逻辑混淆),同时它受到互斥锁的保护!

当另一个线程访问_container 而没有在相同的mutex 上同步时会发生这种情况

【讨论】:

  • 并没有真正回答 OP 的问题。
  • 不,它没有。他的问题是,他看到函数有两个入口,它们之间没有出口,考虑到互斥锁,这不应该发生。
  • @SergeyA 哦。是的。好点子。没有足够接近地阅读跟踪(专注于所采取的分支)。在这种情况下,它是UB all the way.
猜你喜欢
  • 1970-01-01
  • 2011-03-05
  • 1970-01-01
  • 1970-01-01
  • 2011-01-17
  • 1970-01-01
  • 1970-01-01
  • 2011-02-22
  • 1970-01-01
相关资源
最近更新 更多