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

标签 python multithreading

我有一个 C++ 应用程序,它使用带有 Python C API 的嵌入式 Python 解释器。它可以使用 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 循环并行运行。

提前致谢

保罗

最佳答案

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

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

关于Python 线程不在 C++ 应用程序嵌入式解释器中运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1775612/

相关文章:

python - 一段代码的解释

java - 哪个 CPU 使用率反射(reflect)了真实情况?

python - 分布式调度程序中内存消耗过多的示例示例

c - 多线程-如果满足条件如何停止所有线程?

python - 导入错误 : No module named jinja2

python - Pandas to_csv 不输出文件

python - 如何在python中拼接文件夹中的图像

python - 如何移动或调整 X11 窗口的大小(即使它们已最大化)?

java - 并发 HashMap 删除复杂值

java - 在匿名线程中使用最终变量