【发布时间】: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