I was wondering what the difference is in boost::shared_mutex
and boost::upgrade_mutex
. I wanted to make a multi threaded application that will have multiple frequent readers and one non frequent writer.
I could just use a standard shared_mutex
and a shared_lock
and a unique_lock
. Although this is likely to give me writer starvation.
What I want is: If a reader has a shared lock and a writer is waiting on the lock that no other readers will be given access and they will have to wait on the shared lock.
I can find very little information on boost::upgrade_mutex
, but I think this is what I want?
I made this example (please ignore that the cout
s are happening outside of a lock etc and that I can't control which thread runs first):
#include <iostream>
#include <thread>
#include <boost/thread/locks.hpp>
#include <boost/thread/shared_mutex.hpp>
int main()
{
boost::shared_mutex mutex;
boost::shared_lock<boost::shared_mutex> read_lock(mutex);
std::thread t1([&mutex]()
{
std::cout << "Thread trying to get the unique lock!" << std::endl;
boost::unique_lock<boost::shared_mutex> write_lock(mutex);
std::cout << "Thread got the unique lock!" << std::endl;
});
std::thread t2([&mutex]()
{
std::cout << "Thread trying to get the shared lock!" << std::endl;
boost::shared_lock<boost::shared_mutex> read_lock(mutex);
std::cout << "Thread got the shared lock!" << std::endl;
});
// To make sure the threads ask for the lock before unlocking
sleep(1);
std::cout << "Unlocking first lock" << std::endl;
read_lock.unlock();
t1.join();
t2.join();
}
From my testing, if t1
runs before t2
, t2
also waits on read_lock.unlock();
before proceeding. This is what I want!
I then changed boost::upgrade_mutex
to boost::shared_mutex
(in the template param of the locks as well) and I am seeing exactly the same behaviour. I can't find in the documentation if this is guaranteed or what the difference is.