我有一个 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 循环并行运行。
提前致谢,
Paul
我也遇到过同样的类似问题并找到了解决方案。我知道该线程很旧,但以防万一有人想知道......这是一个代码示例,可以满足您的需要。
#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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)