Python's GIL Global Interpreter Lock

The GIL (Global Interpreter Lock)

 

GIL global interpreter lock locks i.e., a characteristic CPython interpreter. Its role is to ensure that only one thread at a time to execute Python bytecode.

It is not Python features, its presence is CPython memory management mechanism caused. Memory management mechanism of language in general, there are two: 1 2. The reference counting garbage collection. CPython is used in reference counting to manage memory. When a resource reference number is 0, the object will be released. If there is no GIL lock, multiple threads immediate simple operation can also be caused by multiple threads simultaneously modify variables, so obviously prone to error.

GIL then lock it will lead to slower run time? First single-threaded nature of the program has no effect, and even enhance efficiency. Have an impact on the multi-threaded program obviously. But it also depends on the type of multi-threaded programs.

If the IO-intensive program, currently owns the lock of the program will first release the lock, then an IO operation, and then acquire the lock. When a thread releases the lock state of the current thread will present a data structure in global variables PThreadState, the thread when the thread acquired the lock state after the previous recovery. So GIL IO-intensive program is still very friendly.

If the program is CPU-intensive, and it will not be as active as the other thread releases the lock to the IO-intensive programs. Therefore, in CPython performed every 0.05 seconds will be forced to release the lock on the thread switching is achieved.

So in the case of high concurrency to speed up the process you need to use another concept: multi-process.

There are many Python developers want to strive to remove GIL lock, but in order to ensure the safe operation of multi-threaded efficiency but lower.

 


 

RLock (recursive lock)

In order to support multiple requests for the same resource in the same thread, python provides a "recursive lock": threading.RLock. Internal RLock maintains a Lock and a counter variable, counter records the number of times acquire, so that resources can be repeatedly acquire. Acquire a thread until all have been release, other threads to get resources.

Guess you like

Origin www.cnblogs.com/ITs-WHY/p/11576745.html