dimanche 27 mars 2016

Elegant pattern for scoped_lock to access resource?

I have objects in containers that are access-controlled with mutexes. I often do something like:

rsrc *r;
{
    scoped_lock l(mtx);
    r = container.pop( );
}
// ... use r

(I use scoped_lock to ensure clean up after exceptions, etc.) However, I don't like the { ... } block that's not part of an explicit control structure (it's only there to make a scope for the scoped_lock) and I don't like the null initialization of r followed by (probable but not certain) assignment in the { ... } block.

I can do something like this:

inline rsrc *locked_pop( mutex &mtx, container &c ) { scoped_lock l(mtx); return c.pop( ); }

and then

rsrc *r = locked_pop( mtx, container );

which is OK, but I have situations where I need to get several items from same (or different) container, under the same lock.

Do you know of an elegant, general way of doing this? (This is not specifically a Boost question, but I'm using those libraries so a Boost-ism would be fine.)

Aucun commentaire:

Enregistrer un commentaire