[capi-sig] C integration with multithreaded Python script
Andreas Sommer
AndiDog at web.de
Wed Oct 14 22:05:04 CEST 2009
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 testing:
*import* threading, time
*def* handler():
print("a")
time.sleep(0.95)
print("b")
t = threading.Thread(target = handler)
t.start()
And in C++, it's this code:
Py_SetProgramName("test");
Py_Initialize();
*if*(!Py_IsInitialized()) *throw* std::exception();
PyObject *module = PyImport_AddModule("__main__");
PyObject *dict = PyModule_GetDict(module);
printf("1\n");
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"
"t.start()\n");
PyObject *obj = PyRun_String(script, Py_file_input, dict, dict);
printf("2\n");
PyErr_Print();
Py_Finalize();
When executing, the output is
1
a2
as opposed to the expected
1
a
b
2
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
mailing list