What is the global interpreter lock (GIL) in CPython?

前端 未结 8 1926
悲哀的现实
悲哀的现实 2020-11-21 08:53

What is a global interpreter lock and why is it an issue?

A lot of noise has been made around removing the GIL from Python, and I\'d like to understand why that is s

8条回答
  •  误落风尘
    2020-11-21 09:49

    Whenever two threads have access to the same variable you have a problem. In C++ for instance, the way to avoid the problem is to define some mutex lock to prevent two thread to, let's say, enter the setter of an object at the same time.

    Multithreading is possible in python, but two threads cannot be executed at the same time at a granularity finer than one python instruction. The running thread is getting a global lock called GIL.

    This means if you begin write some multithreaded code in order to take advantage of your multicore processor, your performance won't improve. The usual workaround consists of going multiprocess.

    Note that it is possible to release the GIL if you're inside a method you wrote in C for instance.

    The use of a GIL is not inherent to Python but to some of its interpreter, including the most common CPython. (#edited, see comment)

    The GIL issue is still valid in Python 3000.

提交回复
热议问题