mutexes with objects

别等时光非礼了梦想. 提交于 2019-12-03 17:05:48

The straightforward way to make a class threadsafe is to add a mutex attribute and lock the mutex in the accessor methods

class cMyClass {
  boost::mutex myMutex;
  cSomeClass A;
public:
  cSomeClass getA() {
    boost::mutex::scoped_lock lock( myMutex );
    return A;
  }
};

The problem is that this makes the class non-copyable. This is important, especially if you want to store objects of the class in a container.

I can make things work by making the mutex a static.

class cMyClass {
  static boost::mutex myMutex;
  cSomeClass A;
public:
  cSomeClass getA() {
    boost::mutex::scoped_lock lock( myMutex );
    return A;
  }
};

However, this means that every instance of the class blocks when any other instance is being accessed, because they all share the same mutex.

Theoretically, a class containing a non-static mutex can be made copyable by hand coding the copy constructor and assignment operator so as to leave out the mutex. However, this is difficult and tedious to do properly, especially for a class with a large number of attributes that frequently change during development.

If a static mutex that blocks access to all instances of the class when one is blocked is not acceptable, then the best and simplest approach is to maintain the mutexes outside the class. It might seem unfortunate to expose the inner workings of a class in this way, but the alternatives are way more complex, hence unreliable, and I frequently find significant optimizations when the mutexes are handled at the level of the code accessing the class.

You're missing the fact that mutex isn't copyable. What would it mean to make a copy of a mutex? The place to acquire and release the mutex is in Rope::compute, and since all of the threads have to access the same mutex, you'll have to define it in runTest and pass it in by reference or by pointer.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!