
Example for boost shared_mutex (multiple reads/one write)
By: a guest on Jan 28th, 2012 | syntax:
None | size: 1.33 KB | hits: 28 | expires: Never
boost::shared_mutex _access;
void reader()
{
// get shared access
boost::shared_lock lock(_access);
// now we have shared access
}
void writer()
{
// get upgradable access
boost::upgrade_lock lock(_access);
// get exclusive access
boost::upgrade_to_unique_lock uniqueLock(lock);
// now we have exclusive access
}
boost::shared_mutex _access;
void reader()
{
boost::shared_lock< boost::shared_mutex > lock(_access);
// do work here, without anyone having exclusive access
}
void conditional_writer()
{
boost::upgrade_lock< boost::shared_mutex > lock(_access);
// do work here, without anyone having exclusive access
if (something) {
boost::upgrade_to_unique_lock< boost::shared_mutex > uniqueLock(lock);
// do work here, but now you have exclusive access
}
// do more work here, without anyone having exclusive access
}
void unconditional_writer()
{
boost::unique_lock< boost::shared_mutex > lock(lock);
// do work here, with exclusive access
}
#include <boost/thread/locks.hpp>
typedef boost::shared_mutex Lock;
typedef boost::unique_lock< boost::shared_mutex > WrtieLock;
typedef boost::shared_lock< boost::shared_mutex > ReadLock;
Lock myLock;
void ReadFunction()
{
ReadLock r_lock(myLock);
//Do reader stuff
}
void WriteFunction()
{
WriteLock w_lock(myLock);
//Do writer stuff
}