C语言中的Python线程

2024-06-02 08:28:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用C编写一个多线程程序。在创建线程之前,通过调用^{}初始化一个全局python环境。然后,在每个创建的线程中,全局python环境是共享的,每个线程调用一个python方法,参数用C转换。在

{{cd2>

# python part, call the counter function
lib = ctypes.cdll.LoadLibrary(libpycount.so)
for i in xrange(10):
    lib.count()
^{pr2}$

我想这可能是因为我没有以正确的方式管理复杂的线程创建。我在python文档中找到了^{}。在

有什么想法或建议吗?在


Tags: the方法程序参数环境libcounterfunction
2条回答

我的问题已经解决了。你可能对你的问题有更具体的要求,所以我试着用一种更通用的方式来写我的解决方案。希望有帮助。在


-在主C线程中

  • 从一开始就初始化Python环境:
/*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();



-返回主C线程

  • 当每个线程完成其工作时,完成python环境
pthread_join(pthread_id, NULL);
PyEval_RestoreThread(mainThreadState);
Py_Finalize();

问题是Python解释器是否是线程安全的这就是文档所说的在同一个进程空间中运行多个解释器

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.)

……我不认为Python线程与原生线程相同,比如在C/C++ +/P>中找到的

相关问题 更多 >