简体   繁体   English

GIL 是否使 Python 解释器单线程或您的 python 代码单线程

[英]Does GIL make the Python Interpreter single threaded or your python code single threaded

So I have been reading about the GIL but I haven't been able to make a certain subtle distinction.所以我一直在阅读有关 GIL 的信息,但我无法做出某种微妙的区分。 Is the Python interpreter (C process) single threaded itself when it is holding the GIL or can the interpreter be multithreaded (utilizing multiple cores, not the Python threading notion) but can only interpret one user level python thread at a time. Python 解释器(C 进程)在持有 GIL 时是单线程的,还是解释器可以是多线程的(使用多个内核,而不是 Python 线程概念),但只能解释一个用户级别的 Z23EEEB4343BDD5555 线程。

I am thinking about this because I am wondering if a C extension written in Cython did not release the GIL but utilized multiple threads would those threads be able to run on different cores?我正在考虑这个问题,因为我想知道用 Cython 编写的 C 扩展是否没有释放 GIL,而是使用了多个线程,这些线程是否能够在不同的内核上运行? It seems if the user python program was single threaded and called on the Cython code for some long running operation the Cython code could be run on multiple cores without releasing the GIL (assuming no python interaction).如果用户 python 程序是单线程的并且调用 Cython 代码进行一些长时间运行的操作,那么 Cython 代码可以在多个内核上运行而无需释放 GIL(假设没有 python 交互)。 Would it only be important for the Cython code to release the GIL in case the Python code calling on it was multithreaded so that other Python threads could be executed in the meantime by the interpreter while the Cython operation is being run on other cores?只有在调用它的 Python 代码是多线程的情况下,Cython 代码释放 GIL 才重要,以便其他 Python 线程可以同时由解释器执行,而 Cython 操作正在其他内核上运行?

The Global Interpreter Lock is just a lock.全局解释器锁只是一把锁。 It's a lock that must be held to interact with almost every part of the CPython implementation machinery, including the C API, but it cannot do anything a lock cannot do.这是一个必须持有才能与 CPython 实现机制的几乎每个部分交互的锁,包括 C API,但它不能做任何锁不能做的事情。

The GIL will not automatically prevent parallel execution of threads that don't acquire the GIL. GIL 不会自动阻止未获取 GIL 的线程的并行执行。 That means C extensions can run multiple threads in parallel, as long as those threads don't try to hold the GIL and don't do anything that needs the GIL.这意味着 C 扩展可以并行运行多个线程,只要这些线程不尝试持有 GIL 并且不做任何需要 GIL 的事情。

On the other hand, the GIL will not automatically enable parallel execution of threads that don't need the GIL, if those threads try to hold the GIL anyway.另一方面,GIL 不会自动启用不需要 GIL 的线程的并行执行,如果这些线程无论如何都试图持有 GIL。 In particular, if you want to write code in Cython that runs without the GIL, you have to release the GIL explicitly :特别是,如果您想在没有 GIL 的情况下在 Cython 中编写代码,则必须显式释放 GIL

with nogil:
    ...

You can also mark a function as safe to call without the GIL by putting nogil in the function header:您还可以通过将nogil放入 function header 来将 function 标记为可以在没有 GIL 的情况下安全调用:

cdef void my_gil_free_func(int spam) nogil:
    ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM