0

I am working on the code below and when I am running in the main thread returns the correct printing. However, when I am running this function in a different thread (a QThread class) the code freeze in the PyRun_SimpleString function- printing and can not reach a break point below. Also no error is returned. I have noticed that this is happening when the sklearn function is imported. Could tou please help to run it correctly in a QThread class? Any help is highly appreciated!

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("hello1"), PyUnicode_FromString("hello2"));

Py_DECREF(moduleMain);
Py_DECREF(func);
Py_DECREF(args);

PS: Python 3.6.1 |Anaconda (64-bit) 4.4.0

EDIT:

PyEval_InitThreads();
PyEval_SaveThread();
PyGILState_STATE state = PyGILState_Ensure();
\\ code above
Py_DECREF(moduleMain);
Py_DECREF(func);
Py_DECREF(args);
PyGILState_Release(state);
Darkmoor
  • 862
  • 11
  • 29
  • 1
    you did call `PyEval_InitThreads();`? maybe check this [Embedding python in multithreaded C application](https://stackoverflow.com/questions/10625584/embedding-python-in-multithreaded-c-application) – Thomas Jul 06 '18 at 21:47
  • @Thomas thanks for the response. I have tried it before calling the className->start(), in the main thread. Not inside the `run` function in the `QThread` class. – Darkmoor Jul 06 '18 at 21:52
  • @Thomas also I just test it before the `PyImport_ImportModule` but without result. – Darkmoor Jul 06 '18 at 21:54
  • 1
    you will wan't to grab the gil ([PyGILState_Ensure](https://docs.python.org/3/c-api/init.html#c.PyGILState_Ensure)) before you call python from another thread, see here [Non-Python created threads](https://docs.python.org/3/c-api/init.html#releasing-the-gil-from-extension-code) – Thomas Jul 06 '18 at 22:01
  • @Thomas it worked thank you very much! I followed your first comment guidelines (@forman post) and it is ok. – Darkmoor Jul 06 '18 at 22:20

0 Answers0