0

我正在扩展一个代码库,请查看以下从类中提取的代码片段。为了不让您感到困惑,我尽可能简单:

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 最初被输入两次(并且与其余逻辑混淆),同时它受到互斥锁的保护!

我很欣赏你的解决方案。谢谢

4

1 回答 1

-1

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

当另一个线程访问_container而没有在同一个mutex.

于 2015-10-09T18:46:26.533 回答