Python的code调用创建操作系统的线程,最终调用Python回调的C库 [英] Python code calls C library that create OS threads, which eventually call Python callbacks

查看:228
本文介绍了Python的code调用创建操作系统的线程,最终调用Python回调的C库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果独一无二的Python间preTER是当操作系统调度另一个线程,它调用一个Python回调执行字节code的中间 - 发生了什么?我是否有权关注这个设计的可靠性?

If the one and only Python interpreter is in the middle of executing a bytecode when the OS dispatches another thread, which calls a Python callback - what happens? Am I right to be concerned about the reliability of this design?

推荐答案

在一般情况下,C库需要调用 PyEval_InitThreads()产卵任何线程之前获得GIL调用蟒蛇回调。而回调需要与 PyGILState_Ensure包围() PyGILState_Release(),以确保安全运行。

In general situations, the C library needs to call PyEval_InitThreads() to gain GIL before spawning any thread that invokes python callbacks. And the callbacks need to be surrounded with PyGILState_Ensure() and PyGILState_Release() to ensure safe execution.

但是,如果C库的,也就是说,一个蟒蛇C扩展的范围内运行,那么也有简单的情况下,它是安全的忽略GIL操控的。

However, if the C library is running within the context of, say, a python C extension, then there are simple cases where it is safe to omit GIL manipulation at all.

想到这调用序列:1)蟒蛇code调用C函数富() 2)富()产卵运行另一个C函数的且只有一个的线程巴(),它回调到Python code和3)富()总是连接或取消运行 bar()的线程返回前。

Think of this calling sequence: 1) python code calls C function foo(), 2) foo() spawns one and only one thread that runs another C function bar(), which calls back to python code, and 3) foo() always joins or cancels the thread running bar() before returns.

在这种情况下,它是安全的省略GIL操纵。因为富()拥有的GIL的生命周期中(即隐含从Python code调用它借来的),以及执行的生命周期foo中使用Python回调()被序列(即只有一个回调线程和Python code并不包含线程)。

In such a case, it is safe to omit GIL manipulation. Because foo() owns the GIL (i.e. implicitly borrowed from the python code that calls it) during its lifecycle, and the execution of python callbacks within the lifecycle of foo() is serialized (i.e. only one callback thread and python code does not incorporate threading).

这篇关于Python的code调用创建操作系统的线程,最终调用Python回调的C库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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