rahman
rahman

Reputation: 4948

boost::scoped_lock not working (for me)

I am extending a code base,Have a look at the following code snippet taken out of a class. I made it as simple as possible not to confuse you:

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;
    }
}

and I get this in stdout:

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

....and so on. signal() is not called. I printed this to show that we are operating on the same object.

How possibly/in what kind of scenarios can happen? `'foo is entered twice initially (and messes with the rest of the logic) while it is being protected by a mutex!

I appreciate your solutions. Thank you

Upvotes: 0

Views: 258

Answers (1)

sehe
sehe

Reputation: 393769

How possibly/in what kind of scenarios can happen? `'foo is entered twice initially (and messes with the rest of the logic) while it is being protected by a mutex!

This would happen when another thread accesses _container without synchronizing on the same mutex.

Upvotes: -1

Related Questions