Python:GIL上下文-切换 [英] Python: GIL context - switching

查看:76
本文介绍了Python:GIL上下文-切换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我通常对 全局解释器锁定的理解非常好(GIL)在Python中有效.本质上,在解释程序运行时,一个线程将GIL保留N个滴答声(其中可以使用sys.setcheckinterval设置N),此时释放GIL,而另一个线程可以获取GIL.如果一个线程开始I/O操作,也会发生这种情况.

So, I generally have a pretty good understanding of how the Global Interpreter Lock (GIL) in Python works. Essentially, while the interpreter is running, one thread holds the GIL for N ticks (where N can be set using sys.setcheckinterval), at which point the GIL is released and another thread can acquire the GIL. The also happens if one thread begins an I/O operation.

我有点困惑的是这一切如何与C扩展模块一起工作.

What I'm a bit confused about is how this all works with C extension modules.

如果您有一个C扩展模块来获取GIL,然后使用PyEval_EvalCode执行一些python代码,那么解释器可以释放GIL并将其提供给其他线程吗?还是获取GIL的C线程将永久保留GIL,直到PyEval_EvalCode返回并且GIL在C中显式释放?

If you have a C extension module that acquires the GIL, and then executes some python code using PyEval_EvalCode, can the interpreter release the GIL and give it to some other thread? Or will the C thread that acquired the GIL hold the GIL permanently until PyEval_EvalCode returns and the GIL is explicitly released in C?

PyGILState gstate = PyGILState_Ensure();

....

/* Can calling PyEval_EvalCode release the GIL and let another thread acquire it?? */
PyObject* obj = PyEval_EvalCode(code, global_dict, local_dict); 

PyGILState_Release(gstate);

推荐答案

是的,解释器始终可以释放GIL;在解释了足够多的指令后,它将自动将其分配给其他线程;如果执行了某些I/O,则将自动分配给其他线程.请注意,自最近的Python 3.x起,准则不再基于执行的指令数,而是基于是否经过了足够的时间.

Yes, the interpreter can always release the GIL; it will give it to some other thread after it has interpreted enough instructions, or automatically if it does some I/O. Note that since recent Python 3.x, the criteria is no longer based on the number of executed instructions, but on whether enough time has elapsed.

要获得不同的效果,您需要一种以原子"方式获取GIL的方式,方法是要求在明确释放GIL之前不释放GIL.到目前为止,这是不可能的(但请参见 https://bitbucket.org/arigo/cpython-withatomic (用于实验版本).

To get a different effect, you'd need a way to acquire the GIL in "atomic" mode, by asking the GIL not to be released until you release it explicitly. This is impossible so far (but see https://bitbucket.org/arigo/cpython-withatomic for an experimental version).

这篇关于Python:GIL上下文-切换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆