bythescruff
bythescruff

Reputation: 1899

How to hold a Boost upgradable_lock for the lifetime of an object?

I'm implementing a pair of classes for interprocess communication where one process will be the only writer and there will be many readers. One class handles reading; one handles writing. To prevent any other process from ever becoming the writer, I want a single object of the writer class which keeps an upgradable lock on a boost::named_upgradable_mutex for its entire lifetime. To that end, the writer class has a member variable of type boost::interprocess::upgradable_lock which is handed the mutex when the object is constructed. When it's time for the writer process to write, it calls the writer class's Write() method, which should upgrade that lock to be exclusive, perform the write, and atomically demote the exclusive lock to be merely upgradable again.

I've managed to implement the first part - upgrading the lock to be exclusive - in my writer class's Write() method by following the Boost documentation on Lock Transfers Through Move Semantics. However, the second part - demoting the lock to be upgradable - results in a new local variable of type boost::interprocess::upgradable_lock which will go out of scope and release the mutex when Write() returns. I need to put that upgradable lock back in my class's upgradable_lock member variable so the upgrade capability will remain solely in my writer object. What's the best way to do this? The only thing I've managed to come up with is to swap the local variable with my member variable before returning. The code looks like this:

using boost::interprocess;
scoped_lock<named_upgradable_mutex> my_exclusive_lock(move(m_lock));

//  do write here

upgradable_lock<named_upgradable_mutex> my_demoted_lock(move(my_exclusive_lock));
m_lock.swap(my_demoted_lock);  //  how else to do this?

This works, but that last line was really counterintuitive and took me a while to think of. Is there a better way? Is it possible to put the demoted lock directly into my member variable? Also, are there any unintended consequences of reusing the member variable to store the demoted lock?

Upvotes: 1

Views: 621

Answers (1)

Tanner Sansbury
Tanner Sansbury

Reputation: 51881

Consider using the move assignment operator. The following code using swap():

upgradable_lock<named_upgradable_mutex> my_demoted_lock(move(my_exclusive_lock));
m_lock.swap(my_demoted_lock);

would become:

m_lock = upgradable_lock<named_upgradable_mutex>(move(my_exclusive_lock));

In this particular case, swap() and the move assignment operator are interchangeable without any side effects because m_lock is in the default constructed state (m_lock.owns() == false and m_lock.mutex() == 0).


I cannot think of any unintended consequences of reusing the member variable for the upgradeable lock. However, there are a few topics to consider:

  • One goal is "to prevent any other process from ever becoming the writer". With the lock being acquired in the Writer constructor, the code is preventing other processes from creating a Writer, in addition to preventing other processes from writing. As a result, the blocking call may be imposing or inconvenient to application code. Consider the following code:

    Reader reader;
    Writer writer; // This may block, but the application code cannot react
                   // to it without dedicating an entire thread to the
                   // construction of the writer.
    

    A compromising alternative may be to try to acquire the lock via this constructor, then add member functions to Writer that provide the application more control. While this would still allow other processes to create a Writer, it prevents more than one from having the privilege to write:

    class Writer
    {
    public:
      bool IsPrivileged();         // Returns true if this the privileged Writer.
      bool TryBecomePrivileged();  // Non-blocking attempt to become the
                                   // privileged Writer.  Returns true on success.
      bool BecomePrivileged();     // Blocks waiting to become the privileged
                                   // Writer.  Returns true on success.
      void RelinquishPrivileges(); // We're not worthy...we're not worthy...
    
      enum Status { SUCCESS, NOT_PRIVILEGED };
      Status Write( const std::string& ); // If this is not the privileged Writer,
                                          // then attempt to become it.  If the
                                          // attempt fails, then return
                                          // NOT_PRIVILEGED.
    };
    
  • Within the Writer::Write() method, if any of the calls in the "do write here" code throw an exception, then the stack will unwind, resulting in:

    • my_exclusive_lock releasing the exclusive lock, allowing other processes to obtain the upgradeable lock.
    • m_lock not having a handle to the mutex, as m_lock.mutex() is set to null when ownership was transferred to my_exclusive_lock in the move.
    • Further calls to Writer::Write() would attempt to write without acquiring the exclusive lock! Even if m_lock had a handle to the mutex, m_lock.owns() would be false, so a transfer to my_exclusive_lock would not attempt to lock.

Here is an example program:

#include <boost/interprocess/sync/named_upgradable_mutex.hpp>
#include <boost/interprocess/sync/sharable_lock.hpp>
#include <boost/interprocess/sync/upgradable_lock.hpp>
#include <boost/move/move.hpp>
#include <iostream>

int main()
{
  namespace bip = boost::interprocess;
  typedef bip::named_upgradable_mutex mutex_t;

  struct mutex_remove
  {
    mutex_remove()  { mutex_t::remove( "example" ); }
    ~mutex_remove() { mutex_t::remove( "example" ); }
  } remover;

  // Open or create named mutex.
  mutex_t mutex( bip::open_or_create, "example" );

  // Acquire upgradable lock.
  bip::upgradable_lock< mutex_t > m_lock( mutex, bip::try_to_lock );
  std::cout << "upgradable lock own:  " << m_lock.owns()
            << " -- mutex: "            << m_lock.mutex() 
            << std::endl;

  // Acquire the exclusive lock.
  {
    std::cout << "++ Entering scope ++" << std::endl;
    std::cout << "Transferring ownership via move: Upgradable->Scoped"
              << std::endl;
    bip::scoped_lock< mutex_t > exclusive_lock( boost::move( m_lock ) );
    std::cout <<   "upgradable lock owns: " << m_lock.owns()
              << " -- mutex: "              << m_lock.mutex()
              << "\nexclusive lock owns:  " << exclusive_lock.owns() 
              << " -- mutex: "              << exclusive_lock.mutex()
              << std::endl;

    // do write here...

    // Demote lock from exclusive to just an upgradable.
    std::cout << "Transferring ownership via move: Scoped->Upgradable"
              << std::endl;
    m_lock = bip::upgradable_lock< mutex_t >( boost::move( exclusive_lock ) );
    std::cout <<   "upgradable lock owns: " << m_lock.owns()
              << " -- mutex: "              << m_lock.mutex()
              << "\nexclusive lock owns:  " << exclusive_lock.owns() 
              << " -- mutex: "              << exclusive_lock.mutex()
              << std::endl;
    std::cout << "-- Exiting scope --" << std::endl;
  }
  std::cout << "upgradable lock own:  " << m_lock.owns()
            << " -- mutex: "            << m_lock.mutex() 
            << std::endl;

  return 0;
}

Which produces the following output:

upgradable lock own:  1 -- mutex: 0xbff9b21c
++ Entering scope ++
Transferring ownership via move: Upgradable->Scoped
upgradable lock owns: 0 -- mutex: 0
exclusive lock owns:  1 -- mutex: 0xbff9b21c
Transferring ownership via move: Scoped->Upgradable
upgradable lock owns: 1 -- mutex: 0xbff9b21c
exclusive lock owns:  0 -- mutex: 0
-- Exiting scope --
upgradable lock own:  1 -- mutex: 0xbff9b21c

Upvotes: 1

Related Questions