Pau*_*aul 5 python multithreading
我有一个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)
Run Code Online (Sandbox Code Playgroud)
问题是“运行”仅在控制台中打印一次。
我如何确保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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2511 次 |
| 最近记录: |