7

Stack Overflow has several examples where a function obtains an upgradeable lock first and then obtains exclusive access by upgrading. My understanding is that this can cause deadlocks if not used carefully since two threads may both obtain the upgradeable/shared lock and then both attempt to upgrade, at which point neither can proceed because the other has a shared lock.

What I want is to obtain the exclusive lock first and then downgrade to a shared lock without releasing the lock completely. I cannot find an example of this. Any ideas?

Community
  • 1
  • 1
Elliot Cameron
  • 5,235
  • 2
  • 27
  • 34
  • I may be out of date with the cool kids, but I thought the usual pattern is to try the upgrade and, if it fails, release the lock entirely and start all over again. Obviously this has its drawbacks, but a deadlock isn't one of them :-) – Steve Jessop Nov 04 '13 at 16:51
  • 2
    Two threads cannot obtain an upgradeable lock. Only one upgradeable lock may be held at any time. That's what makes it upgradeable: it blocks on the upgrade until the current shared locks have been released. – Sneftel Nov 04 '13 at 16:51
  • @Ben, how is that different from a unique_lock? – Elliot Cameron Nov 04 '13 at 19:04
  • 2
    It's different in that you can have an upgradeable lock while others have a shared lock. You cannot have a unique lock while others have a shared lock. – Sneftel Nov 04 '13 at 19:18
  • So I can just use the existing examples and immediately upgrade after obtaining the upgradeable lock? – Elliot Cameron Nov 04 '13 at 20:31

2 Answers2

4

Boost offers this functionality through the UpgradeLockable concept. The method you are looking for is unlock_and_lock_shared().

An implementation of this concept is provided by the upgrade_mutex class.

ComicSansMS
  • 51,484
  • 14
  • 155
  • 166
0

It seems the proper way to do this using lock adapters should be something like this:

boost::shared_mutex mtx;

void exclusive_to_shared( )
{
    boost::unique_lock< boost::shared_mutex > unique_lock( mtx );

    // The lock here is exclusive.

    boost::shared_lock< boost::shared_mutex > shared_lock( std::move( unique_lock ) );

    // The lock here is shared.
}

There's an explicit conversion defined from unique_lock's RV refs to shared_lock which calls the unlock_and_lock_shared( ). See this e-mail thread and the source.

Tarc
  • 3,214
  • 3
  • 29
  • 41