title: How to iterate over a container in a thread-safe way?
body: <p>I have a container (C++) on which I need to operate in two ways, from different threads: 1) Add and remove elements, and 2) iterate through its members.  Clearly, remove element while iteration is happening = disaster.  The code looks something like this:</p>
  
  <pre><code>class A
  {
  public:
     ...
     void AddItem(const T&amp; item, int index) { /*Put item into my_stuff at index*/ }
     void RemoveItem(const T&amp; item) { /*Take item out of m_stuff*/ }
     const list&lt;T&gt;&amp; MyStuff() { return my_stuff; } //*Hate* this, but see class C
  private:
     Mutex mutex; //Goes in the *Item methods, but is largely worthless in MyStuff()
     list&lt;T&gt; my_stuff; //Just as well a vector or deque
  };
  extern A a; //defined in the .cpp file
  
  class B
  {
     ...
     void SomeFunction() { ... a.RemoveItem(item); }
  };
  
  class C
  {
     ...
     void IterateOverStuff()
     {
        const list&lt;T&gt;&amp; my_stuff(a.MyStuff());
        for (list&lt;T&gt;::const_iterator it=my_stuff.begin(); it!=my_stuff.end(); ++it)
        {
            ...
        }
     }
  };
  </code></pre>
  
  <p>Again, <code>B::SomeFunction()</code> and <code>C::IterateOverStuff()</code> are getting called asynchronously.  What's a data structure I can use to ensure that during the iteration, <code>my_stuff</code> is 'protected' from add or remove operations?</p>