First, the Gil Basic concept
1.GIL is GLOABL interpreter lock, global interpreter lock. This is a concept introduced in the CPython of one of the Python interpreters, because the Python interpreter we use now is the CPython interpreter, so Gil is often mentioned in Python. There is no Gil in this Python interpreter in Jpython.
2. Look at Gil from a python design perspective
The execution of the Python code is controlled by the Python virtual machine (also known as the interpreter main loop). Python has been designed to take into account that in the main loop, while only one thread is executing, like running multiple processes in a single-CPU system, there can be multiple programs in memory, but at any moment only one program runs on the CPU. Similarly, while the Python interpreter can "run" multiple threads, only one thread runs in the interpreter at any point in time.
Access to the Python virtual machine is controlled by the global interpreter lock (Global interpreter lock, GIL), which ensures that only one thread is running at the same time.
To make sure that only one thread is running in the processor at any given time.
The Gil solves the problem:
To take advantage of multicore, Python supports multi-threading, but there are data integrity and state synchronization issues between threads, while Gil solves data integrity and state synchronization issues between multithreading (loads locks on lines running on the interpreter, ensuring that only one thread is running in the interpreter at a time).
Effects of Gil:
A loads lock on a thread can have a small effect on Python's multi-threading efficiency, and CPU-intensive operations using multithreading can have frequent context switches and inefficiencies.
In a multithreaded environment, the Python virtual machine executes as follows:
> Set Gil
> switch all one thread to run
> Run: A. Specify the number of bytecode instructions; b. The thread actively yields control;
> Set the thread to sleep
> Unlock Gil
> Repeat all of the above steps again
3. How to avoid the impact of Gil
> Replace thread with multiprocessing
> with other Python interpreters
Python High performance programming--002--Global interpreter lock Gil