gpt4 book ai didi

C中的Python线程

转载 作者:太空狗 更新时间:2023-10-29 21:04:07 28 4
gpt4 key购买 nike

我正在用 C 编写一个多线程程序。在创建线程之前,通过调用 Py_Initialize() 来初始化全局 python 环境。 .然后,在每个创建的线程中,共享全局python环境,每个线程调用一个python方法,参数在C中转换。直到这里一切正常。

当我在加载的 Python 模块中使用 time.sleep() 时,C 程序引发了一个 Segmentation Fault。此外,加载的 python 模块应该加载另一个 C 库以继续工作。我编写了以下愚蠢的计数器库来测试它:

# python part, call the counter function
lib = ctypes.cdll.LoadLibrary(libpycount.so)
for i in xrange(10):
lib.count()
// C part, dummy countings
#include <stdio.h>
int counter = 1;
void
count() {
printf("counter:%d \n", counter);
counter++;
}

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

有什么想法或建议吗?

最佳答案

我的问题已经解决了。您的问题可能更具体,所以我试图在这里以更通用的方式编写我的解决方案。希望对您有所帮助。


- 在主 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 线程:
pthread_create(pthread_id, NULL, thread_entrance, NULL);



- 在每个线程中,或者我们可以在 thread_entrance 函数体中说

  • 准备环境:
/*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();

关于C中的Python线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6596016/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com