/*define a global variable to store the main python thread state*/
PyThreadState * mainThreadState = NULL;
if(!Py_IsInitialized())
Py_Initialize();
mainThreadState = = PyThreadState_Get();
然后启动C线程:
^{pr2}$
-在每个线程中,或者我们可以说在线程体中的入口函数
准备环境:
/*get the lock and create new python thread state*/
PyEval_AcquireLock();
PyInterpreterState * mainInterpreterState = mainThreadState->interp;
PyThreadState * myThreadState = PyThreadState_New(mainInterpreterState);
PyEval_ReleaseLock(); /*don't forget to release the lock*/
/*
* some C manipulations here
*/
将嵌入的Python代码放在此处:
/*get the lock and put your C-Python code here*/
PyEval_AcquireLock();
PyThreadState_Swap(myThreadState); /*swap your python thread state*/
PyEval_CallObject(py_function, py_arguments);
/*or just something like PyRun_SimpleString("print \"hello world\""); for test*/
PyThreadState_Swap(NULL); /*clean the thread state before leaving*/
PyEval_ReleaseLock();
Bugs and caveats: Because sub-interpreters (and the main interpreter)
are part of the same process, the insulation between them isn't
perfect for example, using low-level file operations like
os.close() they can (accidentally or maliciously) affect each other's
open files. Because of the way extensions are shared between
(sub-)interpreters, some extensions may not work properly; this is
especially likely when the extension makes use of (static) global
variables, or when the extension manipulates its module's dictionary
after its initialization. It is possible to insert objects created in
one sub-interpreter into a namespace of another sub-interpreter; this
should be done with great care to avoid sharing user-defined
functions, methods, instances or classes between sub-interpreters,
since import operations executed by such objects may affect the wrong
(sub-)interpreter's dictionary of loaded modules. (XXX This is a
hard-to-fix bug that will be addressed in a future release.)
我的问题已经解决了。你可能对你的问题有更具体的要求,所以我试着用一种更通用的方式来写我的解决方案。希望有帮助。在
-在主C线程中
- 然后启动C线程:
^{pr2}$-在每个线程中,或者我们可以说在线程体中的入口函数
-返回主C线程
问题是Python解释器是否是线程安全的这就是文档所说的在同一个进程空间中运行多个解释器
……我不认为Python线程与原生线程相同,比如在C/C++ +/P>中找到的
相关问题 更多 >
编程相关推荐