Real Multithreading is Coming to Python — Learn How You Can Use It Now

<p>Python is 32 years old language, yet it still doesn&rsquo;t have proper, true parallelism/concurrency. This is going to change soon, thanks to the introduction of a&nbsp;<em>&ldquo;Per-Interpreter GIL&rdquo;</em>&nbsp;(Global Interpreter Lock) which will land in Python 3.12. While the release of Python 3.12 is some months away, the code is already there, so let&rsquo;s take an early peek at how we can use it to write truly concurrent Python code using sub-interpreters API.</p> <h1>Sub-Interpreters</h1> <p>Let&rsquo;s first explain how this&nbsp;<em>&ldquo;Per-Interpreter GIL&rdquo;</em>&nbsp;solves Python&rsquo;s lack of proper concurrency.</p> <p>Simply put, GIL or Global Interpreter Lock is a mutex that allows only one thread to hold control of the Python interpreter. This means that even if you create multiple threads in Python (e.g. using&nbsp;<code>threading</code>&nbsp;module) only one thread at a time will run.</p> <p>With the introduction of&nbsp;<em>&ldquo;Per-Interpreter GIL&rdquo;</em>, individual Python interpreters don&rsquo;t share the same GIL anymore. This level of isolation allows each of these sub-interpreters to run&nbsp;<em>really</em>&nbsp;concurrently. This means, that we can bypass Python&rsquo;s concurrency limitations by spawning additional sub-interpreters, where each of them will have its own GIL (global state).</p> <p>For a more in-depth explanation, see&nbsp;<a href="https://peps.python.org/pep-0684/" rel="noopener ugc nofollow" target="_blank">PEP 684</a>&nbsp;which describes this feature/change.</p> <h1>Setup</h1> <p>To use this new,&nbsp;<em>bleeding edge</em>&nbsp;feature, we need to install up-to-date Python version, that requires building from source:</p> <p><a href="https://betterprogramming.pub/real-multithreading-is-coming-to-python-learn-how-you-can-use-it-now-90dd7fb81bdf">Read More</a></p>