繁体   English   中英

boost :: scoped_lock不起作用(对我来说)

[英]boost::scoped_lock not working (for me)

我正在扩展代码库,请看以下从类中摘录的代码段。 我尽可能地简化了您,以免混淆您:

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在被互斥锁保护的情况下最初被输入两次(并与其余逻辑混淆)!

感谢您的解决方案。 谢谢

在哪种情况下可能/会发生什么? `'foo在被互斥锁保护的情况下最初被输入两次(并与其余逻辑混淆)!

当另一个线程访问_container而不在同一个mutex _container进行同步时,就会发生这种情况。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM