117 GIL global interpreter lock

A, GIL Global Interpreter Lock

cpython comes with GIL Global Interpreter, GIL is itself a mutex

Key:因为有了GIL全局解释器锁,导致了在同一进程的同一时刻只有一个线程在执行,无法利用多核优势

In fact, even if we write a parallel operation of a thread in the program, because the problem will actually GIL garbage collection mechanism, the operating system scheduling problem, parallel threads will still become a serial, this is the GIL Global Interpreter lock led to the same time in the same process, only one thread is running,

Python Python code executed by a virtual machine (also called the interpreter main loop) controlled. Python early in the design should take into account the main loop, while only one thread execution. While the Python interpreter can "run" multiple threads, but only one thread running in the interpreter at any time.

Access to the Python virtual machine is controlled by the Global Interpreter Lock (GIL), it is this lock ensures that only one thread is running.

In a multithreaded environment, Python virtual machine executes the following manner:

  1. Set GIL;
  2. Switch to a thread to run;
  3. A specified number of byte code instructions or thread initiative to the control (can be called time.sleep (0));
  4. The threads to sleep;
  5. Unlock GIL;
  6. Repeat all the above steps again.

When calling external code (such as C / C ++ extension functions) of, GIL will be locked up until the end of the function (because there is no Python bytecode is run during this time, so do not thread-switching) to write extensions programmers can take the initiative to unlock the GIL.

Second, why have GIL Global Interpreter Lock

Because cpython own garbage collection is not thread safe, so be GIL lock.

Led under the same process, the same time can only run one thread, you can not take advantage of multi-core advantage.

Guess you like

Origin www.cnblogs.com/xichenHome/p/11569073.html