首页 > 解决方案 > 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?

标签: pythonc++multithreadinggil

解决方案


在没有看到任何代码的情况下,我只能推断您的 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 活动被编程来做任何事情


推荐阅读