title: Is this an acceptable way to lock a container using C++?
body: <p>I need to implement (in C++) a thread safe container in such a way that only one thread is ever able to add or remove items from the container. I have done this kind of thing before by sharing a mutex between threads. This leads to a lot of mutex objects being littered throughout my code and makes things very messy and hard to maintain.</p>
  
  <p>I was wondering if there is a neater and more object oriented way to do this. I thought of the following simple class wrapper around the container (semi-pseudo C++ code)</p>
  
  <pre><code> class LockedList {
      private:
          std::list&lt;MyClass&gt; m_List;
  
      public:
          MutexObject Mutex;
   };
  </code></pre>
  
  <p>so that locking could be done in the following way</p>
  
  <pre><code> LockedList lockableList;     //create instance
   lockableList.Mutex.Lock();    // Lock object
  
   ... // search and add or remove items
  
   lockableList.Mutex.Unlock();   // Unlock object
  </code></pre>
  
  <p>So my question really is to ask if this is a good approach from a design perspective? I know that allowing public access to members is frowned upon from a design perspective, does the above design have any serious flaws in it. If so is there a better way to implement thread safe container objects? </p>
  
  <p>I have read a lot of books on design and C++ in general but there really does seem to be a shortage of literature regarding multithreaded programming and multithreaded software design.</p>
  
  <p>If the above is a poor approach to solving the problem I have could anyone suggest a way to improve it, or point me towards some information that explains good ways to design classes to be thread safe??? Many thanks.</p>