Should I notify while holding the lock on a condition or after releasing it?
<p>The <a href="https://docs.python.org/3/library/threading.html" rel="nofollow">Python <code>threading</code> documentation</a> lists the following example of a producer:</p>

<pre><code>from threading import Condition
cv = Condition()

# Produce one item
with cv:
    make_an_item_available()
    cv.notify()
</code></pre>

<p>I had to review threading and I looked at <a href="http://en.cppreference.com/w/cpp/thread/condition_variable/notify_all" rel="nofollow">the C++ documentation, which states</a>:</p>

<blockquote>
  <p>The notifying thread does not need to hold the lock on the same mutex
  as the one held by the waiting thread(s); in fact doing so is a
  pessimization, since the notified thread would immediately block
  again, waiting for the notifying thread to release the lock.</p>
</blockquote>

<p>That would suggest doing something like this:</p>

<pre><code># Produce one item
with cv:
    make_an_item_available()
cv.notify()
</code></pre>

<p>Don't read C++ documentation to understand Python APIs. Per <a href="https://docs.python.org/3/library/threading.html#threading.Condition.notify" rel="nofollow">the actual Python docs</a>:</p>

<blockquote>
  <p>If the calling thread has not acquired the lock when this method is called, a <code>RuntimeError</code> is raised.</p>
</blockquote>

<p>Python explicitly requires that the lock be held while <code>notify</code>ing.</p>

python multithreading python-multithreading