title: what is the best way to synchronize container access between multiple threads in real-time application
body: <p>I have <code>std::list&lt;Info&gt; infoList</code> in my application that is shared between two threads. These 2 threads are accessing this list as follows:</p>
  
  <p><strong>Thread 1</strong>: uses <code>push_back()</code>, <code>pop_front()</code> or <code>clear()</code> on the list (Depending on the situation)
  <strong>Thread 2</strong>: uses an <code>iterator</code> to iterate through the items in the list and do some actions.</p>
  
  <p>Thread 2 is iterating the list like the following:</p>
  
  <pre><code>for(std::list&lt;Info&gt;::iterator i = infoList.begin(); i != infoList.end(); ++i)
  {
    DoAction(i);
  }
  </code></pre>
  
  <p>The code is compiled using GCC 4.4.2.</p>
  
  <p>Sometimes ++i causes a segfault and crashes the application. The error is caused in std_list.h line 143 at the following line:</p>
  
  <pre><code>_M_node = _M_node-&gt;_M_next;
  </code></pre>
  
  <p>I guess this is a racing condition. The list might have changed or even cleared by thread 1 while thread 2 was iterating it.</p>
  
  <p>I used Mutex to synchronize access to this list and all went ok during my initial test. But the system just freezes under stress test making this solution totally unacceptable. This application is a real-time application and i need to find a solution so both threads can run as fast as possible without hurting the total applications throughput.</p>
  
  <p>My question is this:
  Thread 1 and Thread 2 need to execute as fast as possible since this is a real-time application. what can i do to prevent this problem and still maintain the application performance? Are there any lock-free algorithms available for such a problem?</p>
  
  <p>Its ok if i miss some newly added <code>Info</code> objects in thread 2's iteration but what can i do to prevent the iterator from becoming a dangling pointer?</p>
  
  <p>Thanks</p>