且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从C线程调用Python代码

更新时间:2023-11-10 18:01:58

首先,您几乎永远都不想调用PyEval_RestoreThread/PyEval_SaveThread.而是,您要调用包装程序宏Py_BEGIN_ALLOW_THREADS/Py_END_ALLOW_THREADS.为这些宏编写了文档.为什么找不到它?

First, you almost never want to call PyEval_RestoreThread/PyEval_SaveThread. Instead, you want to call the wrapper macros Py_BEGIN_ALLOW_THREADS/Py_END_ALLOW_THREADS. The documentation is written for those macros, which is why you couldn't find it.

无论哪种方式,您都不会使用线程函数/宏来获取GIL.您可以使用它们在获得GIL时暂时释放它们.

Anyway, either way, you don't use the thread functions/macros to acquire the GIL; you use them to temporarily release the GIL when you've acquired it.

那么,您为什么要这么做呢?好吧,在简单的情况下,您不会;您只需要Ensure/Release.但是有时您需要保持Python线程状态直到稍后,但不需要保持GIL(甚至明确需要 not 保持GIL,以允许其他线程继续运行)这样可以向您发出信号).正如文档所解释的,最常见的原因是执行文件I/O或大量的CPU约束计算.

So, why would you ever want to do this? Well, in simple cases you don't; you just need Ensure/Release. But sometimes you need to hold onto your Python thread state until later, but don't need to hold onto the GIL (or even explicitly need to not hold onto the GIL, to allow some other thread to progress so it can signal you). As the docs explain, the most common reasons for this are doing file I/O or extensive CPU-bound computation.

最后,在任何情况下都想调用函数而不是宏吗?是的,如果您想访问隐藏的PyThreadState.如果您没有想到可能要这样做的原因,则可能没有.

Finally, is there any case where you want to call the functions instead of the macros? Yes, if you want access to the stashed PyThreadState. If you can't think of a reason why you might want that, you probably don't have one.