Reputation: 501
I have a situation where I have 3 threads involved. Let's call them A, B, and C. Thread A and B share static data within the same class. Thread C also could potentially be using the same static data. So I created two mutexes. One mutex covers thread A and B sharing data with each other. Another mutex takes care of thread A and C sharing data. One mutex is a boost scoped_lock and another mutex is a lock_guard. Am I doing the right thing here? Basically, some of the methods end up looking like this:
bool CMBTmlBroker::GetTheDatasetListFromTheMB(const std::string &strDatasetTypeShortDisplayName /* use GetTheDatasetTypeShortDisplayName() */,
const std::string &strDatasetType /* can be blank */,
const std::string &strProduct /* can be blank */)
{
boost::recursive_mutex::scoped_lock scoped_lock(GetLock());
boost::lock_guard<boost::mutex> DBDatasetKey2DBDatasetInfoMutex(m_DBDatasetKey2DBDatasetInfoMutex);
...
I want a solution with performance being the biggest concern.
Upvotes: 0
Views: 249
Reputation: 3426
thiton is right, you should have "one mutex per protected data object, not one per thread pair." Any shared writable data must be protected to allow only one thread at a time to modify, and there's no way around that.
Also, if you have lots of mutexes, you must be careful to always aquire and release them in the same order, or else you'll deadlock:
mutex MutexAB;
mutex MutexBC;
Thread A
scoped_lock lAB(MutexAB);
scoped_lock lBC(MutexBC);
Thread B
scoped_lock lBC(MutexBC);
scoped_lock lAB(MutexAB);
These threads will deadlock.
Upvotes: 2