title: Thread safe std::map: Locking the entire map and individual values
body: <pre><code>struct Data
  {
   ...
   CRITICAL_SECTION valLock;
  }    
  std::map&lt;int, Data&gt; mp;
  CRITICAL_SECTION mpLock;
  </code></pre>
  
  <p>I am currently using two critical sections to make this thread safe.</p>
  
  <p>I have to lock both <code>map</code> and <code>Data</code> for updating a <code>Data</code></p>
  
  <pre><code>//Lock mpLock
  //Lock mp[key1].valLock
  mp[key1].something = something_new;
  //unlock mp[key1].valLock
  //unlock mpLock
  </code></pre>
  
  <p>I looked into intel's concurrent hashmap, which does not need two locks and handles this internally.Is there any other way, if i don't want to use intel's tbb. I have only <code>c++ 98</code> support.Can use <code>boost</code> though. Looked into <code>boost::shared_mutex</code>, but could not relate how i can use it in my current scenario.</p>
  
  <p>EDIT:
  Is the lock on container really required? Can't i use <code>Data::valLock</code> to read/write <code>Data</code>.Any insertion in <code>mp</code> is not going to affect the existing iterators, so no lock is needed.Any deletion from <code>mp</code> will be preceded with <code>Data::valLock</code>.What cases could be missed here?</p>
  
  <p>EDIT 2:</p>
  
  <pre><code>UpdateThread()
  {
     //Lock mp[key].valLock
     mp[key].a = b;         //Line 1
     //unlock mp[key].valLock
  }
  
  ReadThread()
  {
      //Lock mp[key].valLock
     something = mp[key].a;   //Line 2
     //unlock mp[key].valLock
  }
  </code></pre>
  
  <p>So i am thinking that Line 2 can execute only if Line 1 has completed(or vice versa) i.e. <code>mp</code> has been updated(along with the map internals).So is it not safe? If not then it means if one thread modifies mp[key1], and another reads mp[key2], this is data race?</p>