gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 01:10:37 24 4
gpt4 key购买 nike

我有一个 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com