[capi-sig] C integration with multithreaded Python script
AndiDog at web.de
Sat Oct 31 21:10:36 CET 2009
I still don't have an answer to this question. Meanwhile I've taken a
look at the Python interpreter source code and couldn't find out how it
manages to keep running while other threads exist. Taking the
/RunModule/ function from the code doesn't help me - same problem: only
the first few instructions of the background thread are executed and
then Python execution ends.
Andreas Sommer wrote:
> Hope this is the right mailing list, please complain if not ;)
> I'm currently experimenting with the integration of Python (2.6)
> scripts into my application, and am using the following script for
> *import* threading, time
> *def* handler():
> t = threading.Thread(target = handler)
> And in C++, it's this code:
> *if*(!Py_IsInitialized()) *throw* std::exception();
> PyObject *module = PyImport_AddModule("__main__");
> PyObject *dict = PyModule_GetDict(module);
> strcpy(script, "import threading, time\n"
> "def handler():\n"
> " print(\"a\")\n"
> " time.sleep(0.95)\n"
> " print(\"b\")\n"
> "t = threading.Thread(target = handler)\n"
> PyObject *obj = PyRun_String(script, Py_file_input, dict, dict);
> When executing, the output is
> as opposed to the expected
> It seems to me that when the main execution path (after t.start())
> finishes, the other thread (called t) is canceled?! Adding t.join() to
> the end of the script gives the expected output, but isn't it possible
> to let PyRun_xxx wait for all remaining threads to end? I know the
> Python interpreter does this, but I didn't get much information from
> its source code (it seems to run scripts with the runpy module).
> Best regards
More information about the capi-sig