One, Gil Global interpreter lock
1, what is the global interpreter lock
Gil is essentially a mutex, equivalent to execute permissions, there will be a Gil within each process, multiple threads within the same process, must rob the Gil before using the CPython interpreter to execute its own code, that is, multiple threads under the same process cannot implement parallelism, but can implement concurrency.
# 1 All data is shared, where the code as a data is shared by all threads (all code for test.py and all code for the CPython interpreter) #2 Threads of the task, all need to use the task code as a parameter to the interpreter code to execute, that is, all the thread to run their own tasks, the first thing to do is to have access to the interpreter code.
For example, the following multiple threads perform the process:
Multiple lines enters upgradeable access to the interpreter's code, that is, get execute permission, and then give the target code to the interpreter code to execute
The code of the interpreter is shared by all threads, so the garbage collection thread can also access the interpreter's code to execute, which leads to a problem: for the same data 100, it is possible that thread 1 executes the x=100 while garbage collection performs the recovery of 100 operations, there is no clever way to solve this problem , is to lock processing, such as Gil, to ensure that the Python interpreter can only execute one task at a time code
2. Why use Gil
Because the garbage collection mechanism of the CPython interpreter is not thread-safe
Second, Gil and lock
(1) Gil is a lock that protects the interpreter level, allowing concurrent use with the CPython interpreter
(2) lock is a custom lock that ensures data security when multiple threads/processes modify the same data so that the data is modified serially
Concurrent Programming (v)--gil Global interpreter locks, deadlock phenomena and recursive locks, semaphores, event events, thread queue