python - 在 python 中线程化 c++ 程序

标签 python c++ multithreading gil

我有一个用 Kivy 编写的 Python 应用程序,它使用 C++ 程序进行高速计算,然后它返回一个值,我的 Python 应用程序使用该值。

C++ 程序封装在 PyBind11 中并导入到应用程序中,然后从 Python 中调用。

我的问题是当执行 C++ 程序时,我的应用程序会停止一小会儿,但我仍然希望在后台继续进行。

我天真地认为这可以通过线程化 C++ 调用来解决,但转念一想,我认为问题出在 GIL 上。我必须解锁 GIL 吗?我该如何实现?

最佳答案

在没有看到任何代码的情况下,我只能推断您的 Python 代码正在等待 C++ 代码完成,然后再执行其他任何操作。这可能意味着以下一项或两项:

  • 你不是unlocking the GIL在 C++ 代码中

    • 根据 Global Interpreter Lock (GIL) — Miscellaneous — pybind11 2.2.3 documentation ,使用 pybind,这应该是这样完成的:

      py::gil_scoped_release release;
      long_running_method();
      py::gil_scoped_acquire acquire;
      

      请注意,您需要 GIL 才能访问任何 Python 机制(包括返回结果)。因此,在发布之前,请确保将您需要的所有数据从 Python 类型转换为 C++ 类型。

  • 您没有任何其他事件的 Python 线程,因此在 C++ 调用正在进行时没有编程的其他 Python 事件来执行任何操作

关于python - 在 python 中线程化 c++ 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55205631/

相关文章:

python - 将 python f-string 与格式结合

python - 如何绘制文本簇?

vb.net - 使用 "Task.WhenAll"时如何控制线程数

java - 通过telnet连接esp8266 android

java - 静态方法、新线程性能问题

python - 如何设置seaborn箱线图的y轴范围?

python - 使用来自不同目录的 Flask 提供单个 index.html

c++ - 使用 sqrt() 和 pow() 函数的不同结果

c++ - MS Visual Studio 2013 上的 std::reference_wrapper

c++ - 如何在没有参数包的情况下扩展模式?