Python线程无法在C++应用程序嵌入解释器中运行

6
我有一个使用Python C API嵌入式解释器的C++应用程序。它可以使用PyRun_SimpleFile和PyObject_CallMethod来评估Python文件和源代码。
现在我有一个Python源代码,其中包含一个已经工作的线程,该线程子类化了threading.Thread并简单地重新实现了run方法:
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)

问题是“running”只在控制台中打印一次。
我该如何确保Python线程与我的C++应用程序GUI循环并行运行?
提前致谢,
保罗

只是检查一下:你是如何调用你的线程的? - int3
我在这里有一个类似问题的答案:[https://dev59.com/imvXa4cB1Zd3GeqPLKFI#30746760] - Bruce
3个回答

3

我曾经遇到了类似的问题,找到了解决方案。虽然这个帖子已经过时了,但如果有人想知道... 这里是一个代码示例,可以满足您的需求。

#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;
}

为什么这对你有效?无限循环是如何起作用的?宏的作用是什么,如何使其不成为无限循环? - undefined

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

1

虽然这个帖子已经很旧了,但是我认为我的答案可能对一些遇到同样问题的人有帮助。

两天前我也遇到了同样的问题,我进行了谷歌搜索,并找到了这个帖子,但是@Reuille的解决方案并没有奏效。

现在我想分享一个我刚刚发现的解决方法:你需要运行

app.exec()

在你的Python脚本中,而不是你的C++主函数中。

编辑: 你可以在我的项目中查看我修复的细节。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接