Ben Reeves Ben Reeves -4 years ago 320
C++ Question

Upgrading boost::shared_lock to exclusive lock

Could someone please explain the correct usage for boost::upgrade_lock. The following code results in a deadlock

//Global
typedef boost::shared_mutex Mutex;
typedef boost::shared_lock<Mutex> ReadLock;
typedef boost::upgrade_lock<Mutex> UpgradeLock;
typedef boost::upgrade_to_unique_lock<Mutex> WriteLock;
Mutex sharedMutex;


//Multi threaded reader and writer
{
ReadLock read(sharedMutex);

for (int ii = 0; ii < vec.size(); ++ii) {
Element e = vec[ii];

if (e.needsUpdating()) {
UpgradeLock upgrade(sharedMutex);

WriteLock write(upgrade)

//Do stuff
}
}
}


It doesn't deadlock if i unlock the read lock with read.unlock() before upgrading. But it seems that this shouldn't be necessary?

Answer Source

In the boost::shared_mutex class (which implements the UpgradeLockable concept), a single thread should not attempt to acquire both a shared and an upgradeable (or unique) lock. At any time, the UpgradeLockable can have N shared locks held (via lock_shared), and 1 upgradeable lock (via lock_upgrade). The upgradeable lock can request that it become a unique lock, which blocks until it can become the exclusive holder, which requires all shared locks be released. It is impossible to convert from a shared lock to a unique lock, or a shared lock to an upgradeable lock without releasing the shared lock first.

Note, the upgradeable lock is not exclusive (other shared locks can be held) just that it has special privileges to increase its strength. Unfortunately, multiple upgradeable threads are not allowed at the same time.

In your case, the same thread is attempting to use lock_shared and lock_upgrade, which will deadlock. You can rewrite it as below, and it won't deadlock, but it's still a single point of contention for all of the readers, since only 1 will hold the upgrade lock at a time. In which case, depending on your other functions, the complexity of a shared_mutex might not be necessary. However, if other functions are still acquiring shared locks, then the below will perform as you expect.

//Multi threaded reader and writer
{
    // Only 1 thread can pass this.  Other shared locks are also valid
    UpgradeLock read(sharedMutex); 

    for (int ii = 0; ii < vec.size(); ++ii) {
        Element e = vec[ii];

        if (e.needsUpdating()) {
            // Blocks here until all shareds are released
            WriteLock write(upgrade)

            //Do stuff
        }
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download