python - Threading a c++ program in python
问题描述
I have a Python application written in Kivy that uses a C++ program for a high speed calculation, then it returns a value and my Python application uses that.
The C++ program is wrapped in PyBind11 and imported into the application and then called from Python.
My issue is when the C++ program is executed, my application stops for a short while and I'd still like things to be going on in the background.
I naively thought this could be solved by threading the C++ call, but on second thoughts I think the issue lies in the GIL. Must I unlock the GIL and how could I achieve this?
解决方案
在没有看到任何代码的情况下,我只能推断您的 Python 代码正在等待 C++ 代码完成,然后再执行任何其他操作。这可能意味着以下两者之一或两者:
您没有在 C++ 代码中解锁 GIL
根据Global Interpreter Lock (GIL) — Miscellaneous — pybind11 2.2.3 文档,使用
pybind
,这应该是这样完成的:py::gil_scoped_release release; long_running_method(); py::gil_scoped_acquire acquire;
请注意,您需要 GIL 才能访问任何 Python 机器(包括返回结果)。因此,在发布之前,请确保将所需的所有数据从 Python 类型转换为 C++ 类型。
您没有任何其他活动的Python线程,因此在 C++ 调用正在进行时,没有其他 Python 活动被编程来做任何事情
推荐阅读
- python - 抓取大型复杂的 PDF 表格
- python - zsh:找不到命令:ampy
- java - 通过单个属性更新 JavaFX TableView 并用行颜色反映它
- css - Flexbox 和调整元素大小有问题
- audio - 取youtube视频元素的音频
- firebase - 如何在 Firestore 的文档中添加新的增量字段值?
- spring-boot - 即使角色不同,Spring Boot HttpSecurity 也会重定向到 defaultSuccessUrl
- reactjs - 无法让 componentDidMount() 通过 this.setState 使用获取的 JSON 数据更新空数组
- swift4 - 在 Alamofire 5 委托 Swift5 中缺少 sessionDidReceiveChallenge
- svg - Viz.js 未能在生产构建中将 DOT 渲染为 SVG