Why do we need locks for threads, if we have GIL?
<p>I believe it is a stupid question but I still can't find it. Actually it's better to separate it into two questions:</p>

<p>1) Am I right that we could have a lot of threads but because of GIL in one moment only one thread is executing?</p>

<p>2) If so, why do we still need locks? We use locks to avoid the case when two threads are trying to read/write some shared object, because of GIL twi threads can't be executed in one moment, can they?</p>

<p>At any moment, yes, only one thread is executing Python code (other threads may be executing some IO, NumPy, whatever).  That is mostly true.  However, this is trivially true on any single-processor system, and yet people still need locks on single-processor systems.</p>

<p>Take a look at the following code:</p>

<pre><code>queue = []
def do_work():
    while queue:
        item = queue.pop(0)
        process(item)
</code></pre>

<p>With one thread, everything is fine.  With two threads, you might get an exception from <code>queue.pop()</code> because the other thread called <code>queue.pop()</code> on the last item first.  So you would need to handle that somehow.  Using a lock is a simple solution.  You can also use a proper concurrent queue (like in the <code>queue</code> module)--but if you look inside the <code>queue</code> module, you'll find that the <code>Queue</code> object has a <code>threading.Lock()</code> inside it.  So either way you are using locks.</p>

<p>It is a common newbie mistake to write multithreaded code without the necessary locks.  You look at code and think, "this will work just fine" and then find out many hours later that something truly bizarre has happened because threads weren't synchronized properly.</p>

<p>Or in short, there are many places in a multithreaded program where you need to prevent another thread from modifying a structure until you're done applying some changes.  This allows you to maintain the invariants on your data, and if you can't maintain invariants, then it's basically impossible to write code that is correct.</p>

<p>Or put in the shortest way possible, "You don't need locks if you don't care if your code is correct."</p>

python multithreading