簡體   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