Gil in Python
Published: 2024-03-27 02:35:25

<p>In Python, the<strong> global interpreter lock </strong>commonly known as <strong>GIL </strong>is a mechanism that is used to ensure that only a single thread can access the interpreter at a time.&nbsp;</p>

<h3>A brief overview of threads and multithreading.</h3>

<p>A thread can be thought of as a smaller unit of a process/program that is executed&nbsp;independently of other threads within the same process. A single process can have multiple threads concurrently. All the threads running in a single process shares same resources and can directly access common data.&nbsp;</p>

<p><a href="https://www.pynerds.com/multithreading-in-python/">Multithreading</a> is what it is called when two or more threads in a single&nbsp; process are executed in overlapping&nbsp; periods of time. It offers a lightweight and very convenient way to execute multiple tasks concurrently.</p>

<p>The following example shows a basic multithreading program.</p>

<div class="example">
<pre>
<code class="language-python">import threading
import time

#print capital letters
def task1():
    for letter in "ABCDE":
        print(letter)
        time.sleep(0.5) #cause a small delay

#print digits
def task2():
    for letter in "12345":
        print(letter)
        time.sleep(0.5) #cause a small delay


if __name__ == "__main__":
    # Create two thread for each function/task
    thread1 = threading.Thread(target=task1)
    thread2 = threading.Thread(target=task2)

    #Start the threads
    thread1.start()
    thread2.start()

    # The main thread waits for both threads to finish
    thread1.join()
    thread2.join()
</code></pre>
</div>

<div class="output"><p>Output: </p>
<p>A<br />
1<br />
B<br />
2<br />
C<br />
3<br />
D<br />
4<br />
E<br />
5</p>
</div>

<p>If you observe the above output, you can see that the functions are actually been executed in parallel rather than one after the other.&nbsp;</p>

<h3>Why do we need the GIL?</h3>

<p>The fact that threads directly shares resources and data makes communication between them easier and efficient, leading to quicker execution of simultaneous tasks. However, this also comes with its own challenges.&nbsp; Without proper synchronization of the&nbsp;tasks, it can easily lead to data inconsistency&nbsp;and corruption. For&nbsp;example, &nbsp;this would happen if one thread deletes a resources that is&nbsp; been used by other threads.</p>

<p>To avoid situations like one described above, the GIL ensures that only a single threads gets executed by the interpreter at a given time. Multiple threads&nbsp;are executed in turns by switching very rapidly between them. The switching is fast enough to not cause any noticeable delays to the end user. However, it&nbsp;still isn&#39;t&nbsp; true parallelism as the two tasks are not actually been executed in parallel.</p>

<h3>GIL&#39;s Limitations</h3>

<p>The<strong> Global Interpreter Lock&nbsp; </strong>&nbsp;is designed to ensure data integrity in a multi-threaded program. It helps to avoid race conditions and potential data corruption that could occur if multiple threads were allowed to modify shared data simultaneously.</p>

<p>However, despite its role in maintaining data integrity, the GIL also introduces certain limitations and trade-offs.</p>

<p>The two main limitations of the GIL are:</p>

<div>
<ol>
	<li><strong>Limited parallelism:</strong>&nbsp;The GIL limits true parallelism, particularly in CPU-bound tasks. While multiple threads can run concurrently, they are not able to fully utilize multiple CPU cores simultaneously within the same process.</li>
	<li><strong>Performance Bottleneck:</strong> In scenarios where threads spend significant time executing, the GIL can become a performance bottleneck. CPU-bound tasks may not see the expected performance improvements from threading due to the serialization caused by the GIL.</li>
</ol>
</div>

<h3>Dealing with GIL&#39;s Limitations</h3>

<p>To deal with the limitations imposed by the Global Interpreter Lock (GIL) especially in scenarios where true parallelism is needed, one&nbsp;can consider the following approaches:</p>

<h4><strong>Using Multiprocessing</strong>:</h4>

<p>With <strong><a href="https://www.pynerds.com/multiprocessing-in-python/">multiprocessing</a>,&nbsp;</strong>&nbsp;separate processes&nbsp; can be created, each with its&nbsp;own instance of the interpreter. Each process operates independently with its own resources and data. Processes are&nbsp;not affected by the GIL and this allows for true parallelism, as each process can utilize a separate CPU core.&nbsp;</p>

<p>Multprocessing in Python is achieved using the multiprocessing module in the standard library. The module has an interface that is very similar to that of multithreading. This makes it an&nbsp;attractive option for developers who are familiar with threading but need to achieve true parallelism and avoid the Global Interpreter Lock (GIL) limitations.</p>

<p>Using multiprocessing, our previous example would look like:</p>

<div class="example">
<pre>
<code class="language-python">import multiprocessing
import time

#print capital letters
def task1():
    for letter in "ABCDE":
        print(letter)
        time.sleep(0.5) #cause a small delay

#print digits
def task2():
    for letter in "12345":
        print(letter)
        time.sleep(0.5) #cause a small delay


if __name__ == "__main__":
    # Create two processes for each function/task
    thread1 = multiprocessing.Process(target=task1)
    thread2 = multiprocessing.Process(target=task2)

    #Start the threads
    thread1.start()
    thread2.start()

    # The main process waits for both processes to finish
    thread1.join()
    thread2.join()
</code></pre>
</div>

<div class="output"><p>Output: </p
<p>A<br />
1<br />
B<br />
2<br />
C<br />
3<br />
D<br />
4<br />
E<br />
5</p>
</div>

<p>As you can see from the above example, multiprocessing is&nbsp;very similar to multithreading if you are already with either.</p>

<h4><strong>Using alternative implementations:</strong></h4>

<p>While CPython, the default implementation of Python, has the GIL, other implementations like <strong>Jython </strong>(Python on the Java Virtual Machine) and IronPython (Python on the .NET Framework) don&#39;t have a GIL. If applicable, one&nbsp;might explore using these alternative implementations.</p>

<div class="related"><h3>Related articles</h3><hr><ul><li><p><a class="text-success" href="https://www.pynerds.com/the-python-interpreter/">The Python Interpreter</a><li><p><a class="text-success" href="https://www.pynerds.com/glob-module-in-python/">glob module in Python</a><li><p><a class="text-success" href="https://www.pynerds.com/introduction-to-concurrent-programming-in-python/">Introduction to concurrent programming in Python</a><li><p><a class="text-success" href="https://www.pynerds.com/multithreading-in-python/">Multithreading in Python</a><li><p><a class="text-success" href="https://www.pynerds.com/multiprocessing-in-python/">Multiprocessing in Python</a><li><p><a class="text-success" href="https://www.pynerds.com/subprocesses-in-python/">Subprocesses in Python</a></ul></div>