Boost logo

Boost :

Subject: Re: [boost] [thread] upgrading read lock to write lock
From: Howard Hinnant (howard.hinnant_at_[hidden])
Date: 2011-02-06 17:15:48


On Feb 6, 2011, at 3:11 PM, Edd Dawson wrote:

> I'm struggling to find the correct incantation to upgrade a (conceptual) read lock to a write lock.
>
> Here's my best guess at what I think should work, but it deadlocks at the highlighted point:
>
>
> #include <iostream>
> #include <iomanip>
> #include <boost/thread/shared_mutex.hpp>
> #include <boost/thread/locks.hpp>
>
> int main()
> {
> using namespace boost;
>
> shared_mutex m;
> shared_lock<shared_mutex> readlock(m);
> // reads go here
> // ...
>
> // Ah, need to write actually.
> // Upgrade to a write lock now.
> upgrade_lock<shared_mutex> uglock(m);
> std::cout << __LINE__ << std::endl;
> upgrade_to_unique_lock<shared_mutex> writelock(uglock); // <-- deadlock?
> std::cout << __LINE__ << std::endl;
>
> return 0;
> }
>
>
> I've been trying this with various combinations of msvc 9, msvc 10, mingw 4.3, boost 1.39 and boost 1.45, but always with the same results.
>
> Could someone kindly put me out of my misery? :)

My implementation of shared/upgrade mutexes and locks is here:

http://home.roadrunner.com/~hinnant/mutexes/shared_mutex

and using that, the following works:

#include <shared_mutex>
#include <mutex>
#include <iostream>
#include <iomanip>

int main()
{

   ting::upgrade_mutex m;
   ting::upgrade_lock<ting::upgrade_mutex> readlock(m);
   // reads go here
   // ...

   // Ah, need to write actually.
   // Upgrade to a write lock now.
   std::cout << __LINE__ << std::endl;
   std::unique_lock<ting::upgrade_mutex> writelock(std::move(readlock));
   std::cout << __LINE__ << std::endl;

   return 0;
}

What I have is similar to boost and I believe you can use this as an example to get your code working with the boost version. There is an explanation at the link above as to how my implementation is supposed to work. It is open source and please feel free to use it if that works better for you.

-Howard


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk