Chris Redford
Chris Redford

Reputation: 17768

Multiple-Reader, Single-Writer Lock in Boost WITH Writer Block

The answer here almost does what I want.

I want a read-write lock that will:

  1. Allow readers to take the lock as long as there is no writer
  2. If a writer tries the lock, block out new readers from taking it but allow old readers to finish before giving the writer the lock
  3. Once the writer releases the lock, allow new readers

The implementation above does not meet criteria (2). It allows new readers to grab the lock and block out the writer until they are finished.

Upvotes: 0

Views: 1087

Answers (2)

Chris Redford
Chris Redford

Reputation: 17768

Found it. I needed unique_lock instead of upgrade_to_unique_lock:

boost::shared_mutex _access;
void reader()
{
    // get shared access
    boost::shared_lock<boost::shared_mutex> lock(_access);
}

void writer()
{
    // wait for old shared access readers to finish
    // but block out new shared access readers
    boost::unique_lock<boost::shared_mutex> uniqueLock(_access);
}

Upvotes: 3

RPM
RPM

Reputation: 1

But here your "writer" method does not have a "lock" attribute. Do you mean that before the "unique_lock" you still need to do the "upgrade_lock"? Something like:

void writer()
{
    // get upgradable access
    boost::upgrade_lock<boost::shared_mutex> lock(_access);

    // get exclusive access
    boost::unique_lock<boost::shared_mutex> uniqueLock(lock);
    // now we have exclusive access
}

Or did you mix attributes and it should be:

void writer()
{
    boost::unique_lock<boost::shared_mutex> uniqueLock(_access);
    // now we have exclusive access
}

Upvotes: 0

Related Questions