Python: What is Global Interpreter Lock? (with examples)

<p>The global interpreter lock (GIL) is a controversial topic in the Python community. It prevents one Python process from executing more than one Python bytecode instruction at any given time.</p> <p>This means that even if we have multiple threads on a machine with multiple cores, a Python process can have only one thread running Python code simultaneously.</p> <p><img alt="" src="https://miro.medium.com/v2/resize:fit:630/0*_f-yDjQEkcSsAj7q.jpg" style="height:394px; width:700px" /></p> <h1>Why?</h1> <p>So why does the GIL exist? The answer lies in how memory is managed in CPython.</p> <p><strong>In CPython, memory is managed primarily by a process known as reference counting.</strong></p> <p>Reference counting works by tracking who currently needs access to a particular Python object, such as an integer, dictionary, or list.</p> <h2>Reference counting</h2> <p>A reference count is an integer keeping track of how many places reference that particular object.</p> <p>When someone no longer needs that referenced object, the reference count is decremented, and when someone else needs it, it is incremented. When the reference count reaches zero, no one is referencing the object, and it can be deleted from memory.</p> <p><a href="https://medium.com/@tomas.svojanovsky11/python-what-is-global-interpreter-lock-with-examples-29d9deb934b">Visit Now</a></p>
Tags: Python CPython