【问题标题】:Python Threads do not run in C++ Application Embedded InterpreterPython 线程不在 C++ 应用程序嵌入式解释器中运行
【发布时间】:2009-11-21 14:24:28
【问题描述】:

我有一个 C++ 应用程序,它使用嵌入式 Python 解释器和 Python C API。它可以使用 PyRun_SimpleFile 和 PyObject_CallMethod 评估 Python 文件和源代码。

现在我有一个 python 源代码,它有一个工作线程,它是 threading.Thread 的子类,并且有一个简单的运行重新实现:

import time
from threading import Thread
class MyThread(Thread):
    def __init__(self):
        Thread.__init__(self)

    def run(self):
        while True:
            print "running..."
            time.sleep(0.2)

问题是“正在运行”在控制台中只打印一次。

如何确保 python 线程继续与我的 C++ 应用程序 GUI 循环并行运行。

提前致谢,

保罗

【问题讨论】:

  • 只是检查一下:你是如何调用你的线程的?
  • 我在here有类似问题的答案

标签: python multithreading


【解决方案1】:

我遇到了同样的类似问题并找到了解决方案。我知道线程已经很老了,但以防万一有人想知道...这是一个代码示例,可以满足您的需要。

#include <Python.h>

#include <iostream>
#include <string>
#include <chrono>
#include <thread>

int main()
{
    std::string script =
        "import time, threading                        \n"
        "" 
        "def job():                                    \n"
        "    while True:                               \n"
        "         print('Python')                      \n"
        "         time.sleep(1)                        \n"
        ""
        "t = threading.Thread(target=job, args = ())   \n"
        "t.daemon = True                               \n"
        "t.start()                                     \n";

    PyEval_InitThreads();
    Py_Initialize();

    PyRun_SimpleString(script.c_str());

    Py_BEGIN_ALLOW_THREADS

    while(true)
    {
        std::cout << "C++" << std::endl;
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    }

    Py_END_ALLOW_THREADS

    Py_Finalize();

    return 0;
}

【讨论】:

    【解决方案2】:

    主线程在做什么?它只是将控制权返回给您的 C++ 应用程序吗?如果是这样,请记住在您的主线程中没有运行任何 Python 代码时释放 GIL(全局解释器锁),否则您的其他 Python 线程将停止等待 GIL 被释放。

    最简单的方法是使用 Py_BEGIN_ALLOW_THREADS / Py_END_ALLOW_THREADS 宏。

    查看文档:http://docs.python.org/c-api/init.html#thread-state-and-the-global-interpreter-lock

    【讨论】:

      【解决方案3】:

      虽然这个帖子很旧,但我认为我的回答可能对遇到同样问题的其他人有所帮助。

      两天前我遇到了同样的问题,我用谷歌搜索,找到了这个帖子,但@Reuille 的解决方案没有运气。

      现在我想分享一个我刚刚找到的解决方法:你必须运行

      app.exec()
      

      在您的 Python 脚本中,而不是在您的 C++ 主函数中。 这是一个奇怪的错误。

      编辑:您可以在我的project 上查看我修复的详细信息。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-03-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-23
        • 2012-05-24
        • 1970-01-01
        • 2014-10-12
        相关资源
        最近更新 更多