Python: multithreading setting the variable once
<p>Does the following code thread-safe?<br>
Will only one/first thread set the variable, set_this_var_only_once?  </p>

<pre><code>set_this_var_only_once = None

def worker():
    global set_this_var_only_once
    if set_this_var_only_once is None:
        set_this_var_only_once = "not None"

for i in range(10):
    t = threading.Thread( target=worker )
    t.daemon=True
    t.start()
</code></pre>

<p>Absolutely not.</p>

<p>It is quite possible that two threads execute this line before executing the next one:</p>

<pre><code>    if set_this_var_only_once is None:
</code></pre>

<p>After that, both threads will execute the next line:</p>

<pre><code>        set_this_var_only_once = "not None"
</code></pre>

<p>You can use <a href="https://docs.python.org/3/library/threading.html#threading.Lock" rel="nofollow">locks</a> to prevent that:</p>

<pre><code>lock = threading.Lock()

def worker():
    lock.acquire()
    if set_this_var_only_once is None:
        set_this_var_only_once = "not None"
    lock.release()
</code></pre>

<p>Only one thread will be able to <em>acquire</em> the lock. If another thread tries to acquire it while it is locked, the call to <code>lock.acquire()</code> will block and wait until the lock is <em>released</em> by the first thread. Then the lock will be acquired by the other thread.</p>

<p>That way it is ensured that the code between <code>lock.acquire()</code> and <code>lock.release()</code> is executed in one thread at a time.</p>

<p><strong>EDIT</strong></p>

<p>As Gerhard pointed in <a href="http://stackoverflow.com/a/40100334/389289">the other answer</a>, you can use the <a href="https://docs.python.org/3/library/threading.html#with-locks" rel="nofollow">context management protocol</a> with locks:</p>

<pre><code>with lock:
    if set_this_var_only_once is None:
        set_this_var_only_once = "not None"
</code></pre>

<p>That will also make sure the lock is correctly released in case of an exception within the locked block.</p>

python multithreading python-2.7