title: Multithreading unordered_map
body: <p>I'm working in a multithreading environment. Basically, I have an <code>unordered_map</code> which could be accessed by multiple threads at the same time. Right now, my algorithm is:</p>
  
  <pre><code>function foo(key) {
    scoped_lock()
    if key exists {
      return Map[key]
    }
  
    value = get_value()
    Map[key] = value
  }
  </code></pre>
  
  <p>Obviously the performance are not good with this implementation. Is there any algorithm/approach that I can use in order to improve performance?</p>
  
  <p><strong>EDIT:</strong></p>
  
  <p>I did a number of tests and I thought about the double-checked locking. So, I modified the code with:</p>
  
  <pre><code>function foo(key) {
    if key exists {
      return Map[key]
    }
  
    scoped_lock()
    if key exists {
      return Map[key]
    }
  
    value = get_value()
    Map[key] = value
  }
  </code></pre>
  
  <p>Actually I only add another check before the scoped_lock(). In this scenario, suppose function is called <code>N</code> times. If the first <code>m</code> calls to <code>foo</code>, where <code>m &lt; N</code>, filled the map and the next <code>N - m</code> calls only get values from the map, I don't need the exclusive access. Moreover, there is another check after the <code>scoped_lock</code> which ensures thread safety. Am I right? In any case, with the first code the execution needs ~208s, while the second one ~200s.</p>