user5093757
user5093757

Reputation: 51

Boost read / write lock in another function

here is the situation

boost::shared_mutex   rwlock;


void test()
{
    boost::unique_lock < boost::shared_mutex > writelock(rwlock); 
    // here we have deadlock
}

int main()
{
    boost::shared_lock < boost::shared_mutex > readlock(rwlock); 
    test();
}

I know that we can do something like that:

{
    boost::upgrade_lock<boost::shared_mutex> upgradeable_lock(rwlock); // here we obtain readlock

    {
       boost::upgrade_to_unique_lock<boost::shared_mutex> uniqueLock(upgradeable_lock); // right now we upgrade readlock to writelock
    }
}

but if like in my first example we have another scope we don't see upgradeable_lock. How to solve that issue ?

Upvotes: 0

Views: 344

Answers (1)

cdonat
cdonat

Reputation: 2822

I assume, that the real code is a lot more difficult, with acquiring read locks all over the place, multiple times in the call stack, and then you need to write somewhere, never anticipated.

I am a guessing a bit here, but if that is true, and you don't want to change that, you'll have to walk up the call path from your writing function, and always release the shared_lock before you do the relevant call, and acquire it again afterwards.

Read / write locks are great, but they tend to mislead developers to use read locks inflationary.

As soon as you can refactor, try and reduce the read locks to just those places, where you really have to read. Keep the critical section as short as possible, and avoid function calls inside, that might acquire that lock as well.

When you have done that, a change to a function, that has to write now as well, will not be a big issue any more. BTW, this will also improve the concurrency, because a writer will have more chances to find a moment, where no reader holds a read lock. You might prefer to do that refactoring now, because it will make life a lot easier afterwards.

Another guess: In case you use these read-locks to have a stable state of the data during a longer process, you might want to rethink that choice now. What you really want then, is some kind of software transactional memory.

Upvotes: 1

Related Questions