QThread(C++) and QTimer failed to call Python
-
-
goal: QThread(C++) child threads call deep learning Python training code, and display the training result (PyObject) on the Qt GUI in the main thread.
-
problem: the main thread displays training results in real time, using QTimer, which convert PyObject objects to C++ variables every 1 second. QTimer periodically accesses variables in PyObject, which will cause access conflicts when child threads call Python modules. The main thread calls the following code in real time:
//Main thread real-time display function void DeepLearning::trainVis() { class PyThreadStateLock PyThreadLock; //Get Python GIL dictGuinfoRealtime = trainThread.dictGuinfoRealtime; //Passes the real-time results of the child thread to the main thread variable //elapsed_runtime //An attempt to access variables in dictGuinfoRealtime will result in an access conflict when the child thread calls the Python module PyObject* elapsedruntime_ = PyDict_GetItemString(dictGuinfoRealtime, "elapsed_runtime"); Py_XDECREF(elapsedruntime_); }
The child thread calls the Python training module as follows:
```C++ //The child thread calls Python training code class PyThreadStateLock PyThreadLock; //Get Python GIL PyObject* pTrainS = PyImport_ImportModule("train");//"Train" is the file name of the training file 'train.py' PyObject* args = PyTuple_New(1); PyObject* TrainFun = PyObject_GetAttrString(pTrainSeg, "main"); if (TrainFun && PyCallable_Check(TrainFun)) { PyTuple_SetItem(args, 0, dictGuinfoRealtime); if (!PyObject_CallObject(TrainFun, args)) //Access conflicts are reported here during training { throw std::exception("PyObject_CallObject failed!"); } } Py_XDECREF(TrainFun); ```
- Struggled for a long time still did not find a solution, please give some advice, thank you!
-
-
Hi and welcome to devnet,
Since your main code is in Python, why not use PySide6 for your GUI ? So you can stay with the same language.
-
Ok, one thing that is not clear with your code explanation: why does the gui poll the algorithm execution every second for results ? Shouldn't the object handling that execution notify the other elements of the application once they are done ?