title: Is collections.defaultdict thread-safe?
body: <p>I have not worked with threading in Python at all and asking this question as a complete stranger.</p>
  
  <p>I am wondering if <a href="http://docs.python.org/2/library/collections.html#collections.defaultdict" rel="noreferrer"><code>defaultdict</code></a> is thread-safe. Let me explain it:</p>
  
  <p>I have</p>
  
  <pre><code>d = defaultdict(list)
  </code></pre>
  
  <p>which creates a list for missing keys by default. Let's say I have multiple threads started doing this at the same time:</p>
  
  <pre><code>d['key'].append('value')
  </code></pre>
  
  <p>At the end, I'm supposed to end up with <code>['value',  'value']</code>. However, if the <code>defaultdict</code> is not thread-safe, if the <strong>thread 1</strong> yields to <strong>thread 2</strong> after checking <code>if 'key' in dict</code> and before  <code>d['key'] = default_factory()</code>, it will cause interleaving, and the other thread will create list in <code>d['key']</code> and append <code>'value'</code> maybe.</p>
  
  <p>Then when <strong>thread 1</strong> is executing again, it will continue from <code>d['key'] = default_factory()</code> which will destroy the existing list and value, and we will end up in <code>['key']</code>.</p>
  
  <p>I looked at <a href="http://hg.python.org/cpython/file/7272ef213b7c/Modules/_collectionsmodule.c#l1484" rel="noreferrer">CPython source code for defaultdict</a>. However, I could not find any locks or mutexes. I guess it is not thread-safe as long as it is documented so. </p>
  
  <p>Some guys last night on IRC said that there is GIL on Python, so it is conceptually thread-safe. Some said threading should not be done in Python. I'm pretty confused. Ideas?</p>