title: Can a value in std::map for a key be locked?
body: <p>I have a simple std::map having key-value. I want this map to be thread safe. I do not want to lock the entire map. Since my threads would be working(update,delete) only on the values for a particular key in the map, I do not wish to lock the entire map. I want the other threads to be able to work on the map, of course not on the locked value. </p>
  
  <p>Would it be advisable or logically correct to lock only the value for a specific key? OR I should think of another data structure?</p>
  
  <p>Update: I just tried a sample example where i have parallel threads updating and inserting in the same map . </p>
  
  <pre><code>#include "stdafx.h"
  #include "stdafx.h"
  #include &lt;iostream&gt;
  #include &lt;map&gt;
  #include &lt;process.h&gt;
  #include &lt;windows.h&gt;
  using namespace std;
  CRITICAL_SECTION CriticalSection; 
  
  
  struct newEntry
  {
      int key;
      char value;
  };
  
  
  std::map&lt;int,char&gt; mapIntChar;
  
  unsigned __stdcall UpdateThreadFunc( void* pArguments )
  {
  
      char *ptr =  (char *) pArguments;
      EnterCriticalSection(&amp;CriticalSection); 
      *ptr = 'Z';
      LeaveCriticalSection(&amp;CriticalSection);
      _endthreadex( 0 );
      return 0;
   } 
  
  unsigned __stdcall InsertThreadFunc( void* pArguments )
  {
  struct newEntry *ptr =  (struct newEntry *) pArguments;
  mapIntChar[ptr-&gt;key] = ptr-&gt;value;
      _endthreadex( 0 );
      return 0;
  }
  
  int _tmain(int argc, _TCHAR* argv[])
  {
      std::map&lt;int,char&gt;::iterator it1;
      unsigned threadID;
      if (!InitializeCriticalSectionAndSpinCount(&amp;CriticalSection, 
      0x00000400) ) 
      return 0;
      mapIntChar[0] = 'A';
      mapIntChar[1] = 'B';
      mapIntChar[2] = 'C';
      mapIntChar[3] = 'D';
  
      HANDLE   hThread;
      int nCount = 0;
      struct newEntry *newIns;
      while ( nCount &lt; 1004)
  {
           it1 = mapIntChar.begin();
      char *ptr = &amp;(it1-&gt;second);
           hThread = (HANDLE)_beginthreadex( NULL, 0, &amp;UpdateThreadFunc, ptr, 0, &amp;threadID );
  
           newIns = new newEntry;
           newIns-&gt;key = rand() % 1000;
           newIns-&gt;value = 'K';
      hThread = (HANDLE)_beginthreadex( NULL, 0, &amp;InsertThreadFunc, newIns, 0, &amp;threadID );
      nCount++;
           delete newIns;
  }
  }
  </code></pre>