he RWMutex has reader's and writer's
lock member functions. All reader locks obtain shared ownership. Any writer
lock obtains exclusive ownership. If the mutex is reader-locked and a writer
lock is requested then this particular request and all new requests (reader or
writer) block until all current reader locks are released. When these reader
locks are released then the exclusive writer lock is granted before any reader
locks are granted. When such writer lock is released then all other requests
race for ownership. If another writer gets it then others wait again. If a
reader gets it then all writers wait until most of the currently locked
readers go through.
The idea of implementation is very simple:
class RWMutex : boost::noncopyable
{
private:
boost::shared_mutex
theGuard;
boost::shared_mutex
theMutex;
public:
void
readerLock()
{
{
boost::shared_lock<boost::shared_mutex>
guard(theGuard);
}
theMutex.lock_shared();
}
void
writerLock()
{
boost::lock_guard<boost::shared_mutex>
guard(theGuard);
theMutex.lock();
}
...
};
The following is the full list of public member functions:
RWMutex();
Constructor, does not throw.
void readerLock();
Locks the mutex for shared access, throws boost::thread_resource_error.
void readerUnlock();
Unlocks the mutex from shared access, does not throw.
void writerLock();
Locks the mutex for exclusive access, throws boost::thread_resource_error.
void writerUnlock();
Unlocks the mutex from exclusive access, does not throw.
void upgradeToWriterLock();
Upgrades shared access to exclusive access, may starve, throws
boost::thread_resource_error.
void upgradeUnlock();
Downgrades to shared lock, does not throw.
bool tryWriterLock();
Attempts to establish exclusive lock, returns true on success, throws
boost::thread_resource_error.
The functionality is similar to the boost::thread except for the described
above treatment of starvation. The ots::threading::RWMutex is encapsulated in
the metafunction ots::config::RWMutex. See the example of use in the section
(
Preventing race condition
section
). Note that the upgradeToWriterLock cannot have the same
functionality as writerLock because it would create unjustified deadlock
situations. It has single level locking and, thus, may starve. Also note, that
using writerLock and upgradeLock to lock the same resource may lead to
deadlock. This property is simply inherited from boost::thread.
|