The Global Interpreter Lock, is a lock that protects access to Python objects and carefully controls thread execution, preventing race concurrency in data access and modification, ensuring that only one thread can execute Python code at a time.
Without the GIL, Python’s memory management can be not thread-safe, it could lead to inconsistencies and crashes. (Deadlocks)
It's very simple, Thread will hold the GIL when it is running, and after running the Thread will release the GIL. The next threads must request access to the GIL in order to execute Opcodes (low-level operations). I draw one example of GIL behavior below:
It means that Python developers can utilize async code, and multi-threaded code and never have to worry about acquiring locks on any variables in the process running or having processes crash from deadlocks.
Instead of using threads, you can use processes to run your algorithms in some cases. For IO/Bound operations Threading and concurrency can allow you to have a better use of your resources, for CPU/Bound operations you can use the multiprocessing library to better resource use.
The above is the detailed content of What is Python GIL? How it works?. For more information, please follow other related articles on the PHP Chinese website!