【发布时间】:2018-07-10 14:13:08
【问题描述】:
我正在尝试从 c++ 调用 python 代码,并且我正在使用以下 QThread 类。
myclassName::myclassName()
{
Py_Initialize();
}
myclassName::~myclassName()
{
Py_Finalize();
}
void myclassName::cpp_wrapper(string out1, string out2){
ThreadState = PyEval_SaveThread();
GILState = PyGILState_Ensure();
Py_DECREF(PyImport_ImportModule("threading"));
PyObject *moduleMain = PyImport_ImportModule("__main__");
PyRun_SimpleString(
"def wrapper(arg1, arg2) : \n"\
" import sklearn \n"\
" print(arg1, arg2) \n"\
);
PyObject *func = PyObject_GetAttrString(moduleMain, "wrapper");
PyObject *args = PyTuple_Pack(2, PyUnicode_FromString(out1.c_str()), PyUnicode_FromString(out1.c_str()));
Py_DECREF(moduleMain);
Py_DECREF(func);
Py_DECREF(args);
PyGILState_Release(GILState);
PyEval_RestoreThread(ThreadState);
}
void myclassName::run()
{
algorithm_wrapper("Hello1", "Hello2");
//here a sginal is emmited to the main thread function to delete myclassName* item.
}
int main(){
myclassName* item = new myclassName();
item->run();
}
执行很好(感谢@Thomas 在上一篇文章中)但是当调用Py_Finalize 时返回以下错误。 Py_Finalize 在执行 python 代码时调用,并向主线程中的插槽发出信号以删除类对象。我还尝试在主线程中初始化和完成 python(再次通过发送信号),但返回了相同的错误。
Exception ignored in: <module 'threading' from 'C:\\Users\\username\\AppData\\Local\\Continuum\\Anaconda3\\Lib\\threading.py'>
Traceback (most recent call last):
File "C:\Users\username\AppData\Local\Continuum\Anaconda3\Lib\threading.py", line 1289, in _shutdown
assert tlock.locked()
你能提供一些帮助吗?
编辑:在@Abid Rahman K 的请求之后。
.h 文件
class myclassName : public QThread
{
Q_OBJECT
public:
myclassName();
~myclassName();
protected:
void run();
private:
QMutex mutex_Python;
};
.cpp 文件
myclassName::myclassName():
mutex_Python(QMutex::Recursive)
{
Py_Initialize();
}
myclassName::~myclassName()
{
Py_Finalize();
}
void myclassName::cpp_wrapper(string out1, string out2){
//ThreadState = PyEval_SaveThread();
//GILState = PyGILState_Ensure();
mutex_Python.lock();
Py_DECREF(PyImport_ImportModule("threading"));
PyObject *moduleMain = PyImport_ImportModule("__main__");
PyRun_SimpleString(
"def wrapper(arg1, arg2) : \n"\
" import sklearn \n"\
" print(arg1, arg2) \n"\
);
PyObject *func = PyObject_GetAttrString(moduleMain, "wrapper");
PyObject *args = PyTuple_Pack(2, PyUnicode_FromString(out1.c_str()), PyUnicode_FromString(out1.c_str()));
Py_DECREF(moduleMain);
Py_DECREF(func);
Py_DECREF(args);
mutex_Python.unlock();
//PyGILState_Release(GILState);
//PyEval_RestoreThread(ThreadState);
}
void myclassName::run()
{
algorithm_wrapper("Hello1", "Hello2");
//here a sginal is emmited to the main thread function to delete myclassName* item.
}
int main(){
myclassName* item = new myclassName();
item->run();
}
【问题讨论】:
-
你能解决这个问题吗?怎么样?
-
@AbidRahmanK 我根据我使用的代码在我的帖子中进行了编辑。老实说,我不记得太多。我希望这会有所帮助。
标签: python multithreading qt qthread